简体   繁体   中英

Pull Data from JSON format using Jquery

I have url like this which is a js file example like this link http://www.mysite.com/json.js and that link will out put a json formatted values like below:

{
"note":null,
"attributes":null,
"total_price":9980,
"total_weight":0,
"item_count":4,
"items":[{
  "id":214597138,
  "title":"Acai +",
  "price":2495,
  "line_price":9980,
  "quantity":4,
  "sku":"",
  "grams":0,
  "vendor":"Delta Labs",
  "variant_id":214597138,
  "url":"/products/acai",
  "image":"http://cdn.shopify.com/s/files/1/0156/4994/products/acai_bottle.png?385",
  "handle":"acai",
  "requires_shipping":true
}],
"requires_shipping":true}

now i wanted to grab that link, then on my jquery how am i going to use that link with json output in order to get the values like the title, url, price, sku, and etc?

i searched on google if there are some functions that can handle this and i found jQuery.getJSON, but i don't really understand that much or is it applicable to my to what i am trying to accomplish?

By the way, http://www.mysite.com/json.js , its json value is dynamic, therefore it is the link i wanted to grab, and output the json content

Here is how I would do it, in an ajax request for example.

$.get('http://www.mysite.com/json.js', function(result) {
   var json = $.parseJSON(result);
   alert(json.title); //Do whatever you want here
});

Make sure your JSON is valid -> http://www.jsonlint.com

To go through every entry in jSON try this:

$.getJSON("url/to/json/file",function(data){
    $.each(data,function(index,element){
        console.log(element.items.url);
    });
});

To get one entry try this (without $.each):

$.getJSON("url/to/json/file",function(data){
    console.log(data.items.url);
});

Make sure it's not a CrossDomain issue! JSON parsing between domains doesn't work in some cases. Make sure it's not one of them. To work with CrossDomain use JSONP. The difference between JSON and JSONP it's that JSONP can support callback and works over crossdomain.

Hope it helps

place that in a variable suppose,

myJSON = $.parseJSON(YOUR_JSON);

then,

myJSON.items[0].url

jQuery.parseJSON

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

Also you can use jQuery.getJSON/

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