一、json数据格式
//第一种 名称/值对{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" } //第二种 数组 { "people": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }, { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb"}, { "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" } ]}将json数据赋值给变量
var people = { "PRogrammers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }, { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" } ], "authors": [ { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" }, { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" }, { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" } ], "musicians": [ { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" }, { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" } ] }访问数组
people.authors[1].genre // Value is "fantasy" people.musicians[3].lastName // Undefined. This refers to the fourth entry, and there isn't one people.programmers[2].firstName // Value is "Elliotte"修改json
people.musicians[1].lastName = "Rachmaninov"; 在将字符串转换为 javaScript 对象之后,就可以像这样修改变量中的数据。转换回json字符串
在 Javascript 中转换: String newJSONtext = people.toJSONString();二、json数组数据的解析
var value1 = [{"c01":"1","c02":"2","c03":"3","c04":"4","c05":"5","c06":"6","c07":"7","c08":"8","c09":"9"}, {"c01":"2","c02":"4","c03":"5","c04":"2","c05":"8","c06":"11","c07":"21","c08":"1","c09":"12"}, {"c01":"5","c02":"1","c03":"4","c04":"11","c05":"9","c06":"8","c07":"1","c08":"8","c09":"2"}];var obj1 = eval(value1);alert(obj1[0].c01);三、 JSON.parse()和JSON.stringify()
1.parse 用于从一个字符串中解析出json 对象。例如
var str='{"name":"cpf","age":"23"}'经 JSON.parse(str) 得到:Object: age:"23" name:"cpf" _proto_:Objectps:单引号写在{}外,每个属性都必须双引号,否则会抛出异常
2.stringify用于从一个对象解析出字符串,例如
var a={a:1,b:2}经 JSON.stringify(a)得到:"{"a":1,"b":2}"新闻热点
疑难解答