1.Create JSON
You can create it like this:
1
2
3
4
5
6
7
8var foo = {
"name" : "Ruan",
"age" : 25,
"bar" : {
"name" : "Qiu",
"age" : 24
}
}
or like this:
1
2
3
4
5
6
7
8
9var foo = {},
bar = {};
foo.name = "Ruan";
foo.age = 25;
bar.name = "Qiu";
bar.age = 24;
foo.bar = bar;
2.Access value in a JSON object
1 | console.log(foo.name); //output: Ruan |
or
1
2console.log(foo["name"]);
console.log(foo["bar"]["name"]);
3.Get values by loop
1 | for(var key in foo) { |
Someone may say that it is exactly javascript object, so what is the difference between json and javascript object?
JSON is:
- It is language agnostic data-interchange format.
- The syntax of JSON was inspired by the JavaScript Object Literal notation, but there are differences between them.
For example, in JSON all keys must be quoted, while in object literals this is not necessary:
1 | // JSON: |
Javascript object can be convered to JSON format by JSON.stringify(obj) which keys/properties names will be quoted automatically. However, it is mandatory(good behavior) to use double quotes when define a JSON object.
4.Use native JSON
1 | //Convert a JavaScript object into a JSON string |
- NOTE: in JavaScript 1.8.5
- Starting in JavaScript 1.8.5 (Firefox 4), JSON.parse() does not allow trailing commas
1 | // both will throw a SyntaxError as of JavaScript 1.8.5 |