如何在js中读取json对象 [英] How to read a json object in js
问题描述
我的控制器有一个方法将jsonArray的字符串表示形式返回为
My controller has a method that is returning string representation of a jsonArray as
jsonArray.toString()
jsonArray.toString()
现在是ajax方法
function loadPropertyFile(url) {
$.ajax({
type: "GET",
url: url,
dataType: "text",
success: function(response){
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
}
解析后的变量obj是
"[{"portal.home":"Home"},{"displaytag.tracking.id":"Item ID"},{"displaytag.tracking.itemName":"Item Name"},{"displaytag.tracking.itemType":"Type"}]"
现在我想从js中的键访问值
Now I want to access the values from the keys in js
即.我想访问键"displaytag.tracking.id"的值
ie. I want to access the value of key "displaytag.tracking.id"
问题是我在执行 console.log(obj [0] ["portal.home"]); 时出现错误 TypeError:obj [0]未定义
Problem is when I am doing console.log(obj[0]["portal.home"]); It is giving me error TypeError: obj[0] is undefined
我该怎么办?
推荐答案
首先,您需要将 JSON字符串解析为JavaScript对象,然后访问所需的属性:
First you need to parse the JSON string into JavaScript object, and then access the required property:
var obj = JSON.parse(json);
console.log(obj[0]["portal.home"]);
在不支持本地JSON的旧版浏览器中,应使用Crockford的 json2.js ,这会给你一个;请不要在JSON上使用eval(),因为它可能导致周围情况非常糟糕.
In older browsers which do not have native JSON support, you should use something like Crockford's json2.js, which will give you one; please don't use eval() on JSON, as it can lead to pretty bad things all around.
这篇关于如何在js中读取json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!