Javascript:解析JSON对象

时间:2013-03-12 13:19:03

标签: c# javascript jquery json

我想解析以下数据,这是来自服务器的对象列表。这是我在数据上使用JSON.stringify(data.d);后的内容:

"[{"__type":"EditGridDemo.CellData","empProperty":"SSN","empValue":"a","isValid":false,"comments":"Reason of what went wrong"},{"__type":"EditGridDemo.CellData","empProperty":"Birth_Date","empValue":"","isValid":false,"comments":"Reason of what went wrong"},{"__type":"EditGridDemo.CellData","empProperty":"Department_Name","empValue":"","isValid":false,"comments":"Reason of what went wrong"},{"__type":"EditGridDemo.CellData","empProperty":"email","empValue":"","isValid":false,"comments":"Reason of what went wrong"},{"__type":"EditGridDemo.CellData","empProperty":"First_Name","empValue":"","isValid":false,"comments":"Reason of what went wrong"},{"__type":"EditGridDemo.CellData","empProperty":"Sex","empValue":"","isValid":false,"comments":"Reason of what went wrong"},{"__type":"EditGridDemo.CellData","empProperty":"Strata_ID","empValue":null,"isValid":false,"comments":"Reason of what went wrong"},{"__type":"EditGridDemo.CellData","empProperty":"SSN","empValue":"b","isValid":false,"comments":"Reason of what went wrong"},{"__type":"EditGridDemo.CellData","empProperty":"Birth_Date","empValue":"","isValid":false,"comments":"Reason of what went wrong"},{"__type":"EditGridDemo.CellData","empProperty":"Department_Name","empValue":"","isValid":false,"comments":"Reason of what went wrong"},{"__type":"EditGridDemo.CellData","empProperty":"email","empValue":"","isValid":false,"comments":"Reason of what went wrong"},{"__type":"EditGridDemo.CellData","empProperty":"First_Name","empValue":"","isValid":false,"comments":"Reason of what went wrong"},{"__type":"EditGridDemo.CellData","empProperty":"Sex","empValue":"","isValid":false,"comments":"Reason of what went wrong"},    
{"__type":"EditGridDemo.CellData","empProperty":"Strata_ID","empValue":null,"isValid":false,"comments":"Reason of what went wrong"}]"

它是一个CellData列表,由empProperty,empValue,isValid,comments作为其属性组成。我无法在JS中访问这些属性。

3 个答案:

答案 0 :(得分:2)

刚开始使用data.d [i] .empProperty和data.d [i] .empValue,如某些注释中所述,i是数组的索引。不要对它进行字符串化,它已经被解析为一个对象。

了解JSON Here

答案 1 :(得分:-1)

结构是一个对象数组。 因此,您只需通过索引访问每个元素:

var arr = JSON.stringify(data.d);
var item = arr[0];

然后您可以通过不同方式访问每个属性:

empValue = item.empValue;  //returns "a"
empProperty = item["empProperty"];  //returns "SSN"

示例here

答案 2 :(得分:-1)

我引用以下链接中的一节: JSON

为了防止这种情况,应该使用JSON解析器。 JSON解析器只能识别JSON文本,拒绝所有脚本。

var jsonData = JSON.stringify(data.d);
var myObject = JSON.parse(jsonData);