0

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.

  • 1
    You parse the JSON back into a JavaScript object, then you can access the properties. – Felix Kling Feb 16 '14 at 21:27
  • possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Felix Kling Feb 16 '14 at 21:28
  • can you be more specific: are you asking how to access the `a` and `b` values in what is already a javascript object, how to access them from inside a JSON serialized string, or some third thing altogether? – Mike 'Pomax' Kamermans Feb 16 '14 at 21:31

1 Answers1

1

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;
OregonTrail
  • 8,594
  • 7
  • 43
  • 58