简体   繁体   中英

json string parse error

I have a Json string as-

var RetailerData = {};

// The object that the JSON string should represent, can use this as it is if you want.

RetailerData.webSites = [
{
    id: 1,
    text: 'J.Crew',
    image: 'images/retailer-logo/jcrew.png',
    extra: 'www.jcrew.com'
},
{
    id: 2,
    text: 'GAP',
    image: 'images/retailer-logo/gap.png',
    extra: 'www.gap.com'
}];

I want to parse it using jquery $.parseJSON to get each value. I have tried it using

var obj = $.parseJSON(RetailerData.webSites);

$.each(obj, function() {
    console.log(this['id']);
});

But getting continuous error in each try. Can anyone tell a proper method for doing this. Thanks in advance.

You're trying to turn a JavaScript object into a JavaScript object, which just doesn't make sense! What you can do is

var str = JSON.stringify(RetailerData.webSites);

and use str to transfer your data somewhere else. Then use

var obj = JSON.parse(str);

to get your original object back after it's been modified (or not) from another source.

You use parseJSON to parse a jsonString to json object.

But in your case RetailerData.webSites is already a json object no need to parse it.

var obj = RetailerData.webSites;

$.each(obj, function() {
    console.log(this['id']);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM