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.
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.
Share Improve this question edited Dec 28, 2010 at 20:09 Buddy asked Dec 28, 2010 at 20:04 BuddyBuddy 1,8463 gold badges20 silver badges28 bronze badges2 Answers
Reset to default 4Have 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/js.html
The reference JSON site can be found here:
http://json/
(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 root site under "JavaScript" language):
https://github./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 remend 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./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>