How to read a json object in js

2019-09-21 06:42发布

My controller has a method that is returning string representation of a jsonArray as

jsonArray.toString()

Now following is the ajax method

function loadPropertyFile(url) {
$.ajax({
    type: "GET",
    url: url, 
    dataType: "text",
    success: function(response){
        var obj = jQuery.parseJSON(response);
        alert(obj);
    }
});

}

Here the variable obj after parsing comes out to be

"[{"portal.home":"Home"},{"displaytag.tracking.id":"Item ID"},{"displaytag.tracking.itemName":"Item Name"},{"displaytag.tracking.itemType":"Type"}]"

Now I want to access the values from the keys in js

ie. I want to access the value of key "displaytag.tracking.id"

Problem is when I am doing console.log(obj[0]["portal.home"]); It is giving me error TypeError: obj[0] is undefined

What shall I do ?

4条回答
手持菜刀,她持情操
2楼-- · 2019-09-21 07:03

You can directly access by following

var data = JSON.parse('[{"Item_Number":"M71118LHB","Description":"MENS ONESIE"}]');
var desc = data[0].Description;
console.log(desc);
查看更多
你好瞎i
3楼-- · 2019-09-21 07:05

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"]);

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.

查看更多
仙女界的扛把子
4楼-- · 2019-09-21 07:07

In case you have the JSON directly in your javascript source (which I don't assume, but I'm adding this for others), you can just remove the quotes, and javascript creates an object based on it:

var obj = [{"portal.home":"Home"},{"displaytag.tracking.id":"Item ID"},{"displaytag.tracking.itemName":"Item Name"},{"displaytag.tracking.itemType":"Type"}];
console.log(obj[0]["portal.home"]);
查看更多
唯我独甜
5楼-- · 2019-09-21 07:12

Use $.parseJSON (or JSON.parse in modern browsers) to convert your string into a Javascript object:

var json = '[{"portal.home":"Home"},{"displaytag.tracking.id":"Item ID"},{"displaytag.tracking.itemName":"Item Name"},{"displaytag.tracking.itemType":"Type"}]';
var object = $.parseJSON(json);

In your case your JSON string will create an array, so you will need to get the object at the correct index:

var portalHomeValue = object[0]["portal.home"];
查看更多
登录 后发表回答