我不知道为什么但是我一直在尝试解析以下json:
{
"output": "",
"status": -1,
"system_messages": {
"error": [],
"success": [
"You have added Steven as a friend."
]
}
}
我如何解析成功'用jquery?
答案 0 :(得分:0)
根据您的真实情况,您需要:
// You really have JSON (that is, you have a *string* containing
// what you quoted):
var data = JSON.parse(theString); // Or ... = jQuery.parseJSON(theString)
console.log(data.system_messages.success[0]);
或只是
// You don't have JSON (anymore), it's already an object:
console.log(yourVariableName.system_messages.success[0]);
请注意,如果你因为ajax调用而得到了回来并且你使用jQuery来进行ajax调用,那么jQuery可能已经已经为你解析它而只需要第二个例子以上。类似地,如果你在代码中有字面引用的内容,那么它不是JSON,它是一个JavaScript对象初始化器,你只需要上面的第二个例子。
请注意,由于success
是一个数组,我们最后需要[0]
。
直播示例:
var theString =
'{' +
'"output": "",' +
'"status": -1,' +
'"system_messages": {' +
'"error": [],' +
'"success": [' +
'"You have added Steven as a friend."' +
']' +
'}' +
'}';
var data = JSON.parse(theString);
snippet.log(data.system_messages.success[0]);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
答案 1 :(得分:0)
使用
var obj={
"output": "",
"status": -1,
"system_messages": {
"error": [],
"success": [
"You have added Steven as a friend."
]
}
}
alert(obj.system_messages["success"][0]);