PHP Noob
PHP Noob

Reputation: 1615

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

Upvotes: 1

Views: 4696

Answers (4)

aki
aki

Reputation: 709

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

Upvotes: 1

swati
swati

Reputation: 1757

jQuery.parseJSON

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

Also you can use jQuery.getJSON/

Upvotes: 0

Nick Barrett
Nick Barrett

Reputation: 1051

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
});

Upvotes: 3

thecodeparadox
thecodeparadox

Reputation: 87073

place that in a variable suppose,

myJSON = $.parseJSON(YOUR_JSON);

then,

myJSON.items[0].url

Upvotes: 0

Related Questions