简体   繁体   中英

Get data from this json string

I have a json string

["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]

I need to get at the data only and I want to extract the string to get the following :

https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg

I have tried to use JSON.parse but this does not seem to work

Any help woul dbe appreciated

[] represents an array on JSON. {} represents an Object.

So in order to fetch the first element from you json string , you have to parse the string as a JSON element ;

var arr = JSON.parse('["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]');

OR when you HAVE a json array already;

var arr = ["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"];

Then, go on and fetch the first value from your array which has index 0 as in all programming languages.

var url = arr[0];

It's seems to be a normal array not a JSON, but if you want you can treat it as JSON:

    var image = JSON.parse('["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]')[0];
console.log(image); //https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg

Be aware of the difference between an array, and a JSON object.

I have given some examples of the differences and how to access them.

 // This is an array containing 1 value. myobj = ["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]; // it can be accessed by either the array name (since it only hase one value) or the array name and index of the value in cases where the array actually has more than one value. var example1 = [myobj]; document.write("This is my single value array:<br>" + example1 + "<br><br>"); // This is probably best practice regardless of the number of items in the array. var example2 = myobj[0]; document.write("Now im specificing the index, incase there are more that one urls in the array:<br>" + example1 + "<br><br>"); // This is a JSON object myJsonObj = {"url":"https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"} // You access the value of the URL like this: var example3 = myJsonObj.url; document.write("Here is the value from a JSON object:<br>" + example3 );

Hope this helps

Just use parse function:

var text = '["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]';
var obj = JSON.parse(text);

https://jsfiddle.net/esouc488/1/

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