In JS we can directly define an object:
var obj={name:"Blue",age:10};
The above is actually the so-called JSON. I will quote other people’s more complicated examples:
{ firstName: "Brett", lastName: "McLaughlin", email: "brett@ jb51.net" }
{ people: [
{ firstName: "Brett", lastName: "McLaughlin", email: "brett@jb51.net" },
{ firstName: "Jason", lastName: "Hunter", email: "jb51 .net" },
{ firstName: "Elliotte", lastName: "Harold", emai": "elharo@jb51.net" }
]}
{ people1: [
{ firstName: "Brett", lastName: "McLaughlin", email: "brett@jb51.net" },
{ firstName: "Jason", lastName: "Hunter", email: "jb51.net" },
{ firstName: "Elliotte", lastName: "Harold", emai": "elharo@jb51.net" }
],
people2: [
{ firstName: "Brett", lastName: "McLaughlin", email: "brett@jb51.net" },
{ firstName: "Jason", lastName:"Hunter", email: "jb51.net" },
{ firstName: "Elliotte", lastName:"Harold ", emai": "elharo@jb51.net" }
],
people3: [
{ firstName: "Brett", lastName: "McLaughlin", email: "brett@jb51.net" } ,
{ firstName: "Jason", lastName: "Hunter", email: "jb51.net" },
{ firstName: "Elliotte", lastName: "Harold", emai": "elharo@jb51. net" }
]
}
2. Format the text transmitted in the background that meets JSON conditions.
Because the biggest use of JSON is AJAX applications, the key is how to convert the text into a javascript object. Assuming that the text we request is data, then we parse it as follows:
data=data.replace(/n | r/g,"");
var obj=eval( '(' data ')');
Because spaces and carriage returns will also be output when we output in the background, so we need to replace them with regular expressions here, and then use eval to convert them into objects. Called.