我有一个json数组
var students = {"apResults":[{"offid":"267","item_name":"","offer_name":"fsdfsf","stlongitude":"77.5945627","stlatitude":"12.9715987"},
{"offid":"265","item_name":"","offer_name":"vess offer shops","stlongitude":"","stlatitude":""},
{"offid":"264","item_name":"","offer_name":"vess ofer shop","stlongitude":"","stlatitude":""},
{"offid":"263","item_name":"","offer_name":"ofer frm vess","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"262","item_name":"","offer_name":"offer hungamma","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"261","item_name":"","offer_name":"offer hungamma","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"260","item_name":"","offer_name":"offer1","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"259","item_name":"","offer_name":"offer","stlongitude":"77.5943760","stlatitude":"12.9716060"}]}
我如何使用json.parse
解析这个json数组。我试过这段代码
for(i=0;i<students.apResults.length;i++)
{
var contact = JSON.parse(students.apResults);
var offid = contact.offid;
alert(offid)
}
但它发出了错误JSON.parse: unexpected character
。编辑了我的问题
答案 0 :(得分:7)
这不是一个json字符串,这是一个常规的javascript变量:
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
答案 1 :(得分:4)
for(i=0;i<students.apResults.length;i++)
{
var contact = JSON.parse(students.apResults[i].offid);
alert(contact)
}
答案 2 :(得分:3)
JSON解析字符串,而不是对象/数组。
为什么需要解析时可以像students.Maths[i].Name
答案 3 :(得分:2)
students
不是JSON数组,它是一个实际的数组。您不必解析,因为它不是字符串。因此,您可以直接访问所需的数据:
for(i=0;i<students.Maths.length;i++) {
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
答案 4 :(得分:2)
您无法解析students
,因为它不是JSON。这是一个简单的对象。
然而,这将有效:
var students = JSON.stringify(students); // if you want to send data
students = JSON.parse(students); // after receiving make a object from it
//use like any object
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
当然,除非您将students
数据发送到其他网站或程序,否则以这种方式编写是没有意义的。
修改强> 您根本不需要此代码中的JSON。但是如果你想测试JSON.parse()就这样做:
var students = { ... } // your data
var students = JSON.stringify(students); // students is `object`, make it `string`
students = JSON.parse(students); // now you can parse it, `students` is object again
for(i=0;i<students.apResults.length;i++) {
var contact = students.apResults; // no JSON
var offid = contact.offid;
alert(offid)
}
这应该有效。
答案 5 :(得分:1)
你拥有的是一个javascript对象。所以,你不需要JSON.parse
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i]);
var fullname = contact.Name;
alert(fullname)
}
这应该没问题
答案 6 :(得分:0)
JSON的想法是交换表示为结构化字符串的对象(简而言之)。你所拥有的只是一个物体。将不是JSON的对象和对象解析为javascript对象是不必要的(也是不可能的);你得到的是你对解析的JSON字符串的期望结果。