Question

This is the outputted JSON data, I need to take values a and add it to b.

{
    protocol: null,
    slashes: null,
    auth: null,
    host: null,
    port: null,
    hostnat null,
    hash: null,
    search: "?t4&bt
    query: {
        a: "t,
        b: t2"
    },
    pathname: "/",
    path: "/?t=4tb=2",
    href: "/?t=4tb=2"
}

Thanks in advance! I know it's probably simple but I'm new to this.

Was it helpful?

Solution

Use JSON.parse. Note that all key names need to be quoted, and single quotes, ', are used on the outside so as not to interfere with the quotes inside the JSON string.

Also, remove the quotes from the numbers if you want them to be treated as numbers.

var urlParams = JSON.parse('{"protocol": null,"slashes": null,"auth": null,"host": null,"port": null,"hostname": null,"hash": null,"search": "?a=4&b=2","query": {"a": 4,"b": 2},"pathname": "/","path": "/?a=4&b=2","href": "/?a=4&b=2"}');

var sum = urlParams.query.a + urlParams.query.b;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top