2

I need to output JSON object, that looks like:

{
    "dynamicvaluenumberone":3,
    "dynamicvaluenumbertwo":7
}

In something, that looks like: dynamicvaluenumberone (3), dynamicvaluenumbertwo(7)

I've found some articles with static values or parsing JSON with jQuery. I don't want to use any framework to do this simple task.

Buddy
  • 1,808
  • 3
  • 19
  • 28

2 Answers2

4

Have you tried JSON.parse?

var json = '{"dynamicvaluenumberone":3, "dynamicvaluenumbertwo":7}';
var obj = JSON.parse(json);

For accessing dynamic keys, you can loop over the keys using for...in:

for(var i in obj) {
    console.log(i + " (" + obj[i] + ")");
}

Update: Depending on the browsers you need to support, the JSON library is also available here: http://www.json.org/js.html

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

The reference JSON site can be found here:

http://json.org/

(it is also linked from the Mozilla article mentioned in Felix's answer).

The reference, browser-independent JavaScript JSON parser can be found here (linked from json.org root site under "JavaScript" language):

https://github.com/douglascrockford/JSON-js

(json2.js is the one you want). The nice thing about Douglas Crockford's reference implementation is that it will use browser-native JSON parser if available (fast, efficient - available on IE8+ in standards mode, latest Opera, Chrome, Safari, FireFox - that's what Felix's link talks about), only falling back to JavaScript implementation (slow) in browsers where native JSON parser is not available.

I've been using json2.js for years and strongly recommend it :-).

Simple example illustrating how to use it (save as e.g. "test.html" and open in any browser):

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>JSON parser test</title>
    </head>
    <body>
        <script type="text/javascript" src="http://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>
        <script type="text/javascript">

            var str = "{ \"dynamicvaluenumberone\":3, \"dynamicvaluenumbertwo\":7, \"dynamicvaluenumberthree\":\"hello\" }";
            var obj = JSON.parse(str);

            alert(
                "Parsed object type: " + typeof obj + "\n" +
                "Value 1: " + obj.dynamicvaluenumberone + " (" + typeof obj.dynamicvaluenumberone + ")\n" +
                "Value 2: " + obj.dynamicvaluenumbertwo + " (" + typeof obj.dynamicvaluenumbertwo + ")\n" +
                "Value 3: " + obj.dynamicvaluenumberthree + " (" + typeof obj.dynamicvaluenumberthree + ")");

        </script>
    </body>
</html>
Milan Gardian
  • 11,326
  • 5
  • 38
  • 45