What is JSON?

JSON is a syntax, a text format that is completely independent of the programming language. You can convert data types represented in any programming language to jSON-formatted strings or vice versa. This allows different programming languages to share data in JSON format. JSON syntax rules, you can see the official website introduction!


Use JSON in JavaScript

JSON is a browser-built object that you can use directly without downloading. There are two methods: json.stringify and json.parse.

1, js array type to JSON string
<script>	
    var  params = [];
    for(var i = 0; i < 3; i++){
        var param = [];
        param.push("one");
        param.push("two");
        param.push("three");
        params.push({"group":i,"param":param});
    }

    var json = JSON.stringify(params);
    alert(json);
</script>

// The output is: [{"group":0,"param":["one","two","three"]},{"group":1,"param":["one","two","three"]},{"group":2,"param":["one","two","th ree"]}]
Copy the code

2. Change the js object type to JSON string
var object = {};
var params = [];
    
for(var i = 0; i < 3; i++){
	var obj = {};	
	obj[i] = "abc";
	params.push(obj);
	
}
object['name'] = 'jack';
object['age'] = 25;
object['data'] = params;
 
var json = JSON.stringify(object);

console.log(json);

/ / output is: {" name ":" jack ", "age" : 25, "data" : [{" 0 ":" ABC "}, {" 1 ":" ABC "}, {" 2 ":" ABC "}]}
Copy the code

Json string to JS data type
var text = '{ "sites" : [' +
  '{ "name":"Learn-anything" , "url":"www.learn-anything.cn" },' +
  '{ "name":"Google" , "url":"www.google.com" },' +
  '{ "name":"Taobao" , "url":"www.taobao.com" } ]}';

obj = JSON.parse(text);
console.log("obj", obj);
Copy the code

Other programming languages use JSON

Each programming language has a corresponding JSON library to use, and the official website lists all available libraries. Check them out here!


Iv. Reference documents
  • How do I use JSON in JavaScript?