简体   繁体   中英

After creating a JSON string, how do I retrieve data from it?

I'm having trouble getting data that I've put into a JSON string in javascript. I first add my values to a JSON object and then I stringify it. I'm not sure I understand why I can't get a value from it. All I see is 'undefined' in the alert.

http://codepen.io/jimmykup/pen/wjJst

var jsonObj = [];

var name = "1stname";
var url = "firsturl";

item = {}
item ["name"] = name;
item ["url"] = url;

jsonObj.push(item);

var jsonString = JSON.stringify(jsonObj);

alert (jsonString.url);

I am converting my object to a string because I will be transferring that text somewhere and only THEN do I need to access the values.

You need to use JSON.parse() to convert a JSON string back into an object. Also, since your object is an array, you need to index it before accessing the url property.

var newObj = JSON.parse(jsonString);
alert (newObj[0].url);

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