Dev Oskii
Dev Oskii

Reputation: 929

Get value of attribute in JSON

I'm trying to isolate the "ip" attribute of a JSON object. The code that gets the JSON object is

var parsed;
$.getJSON('//jsonip.com/?callback=?', function(data) {
    parsed = JSON.stringify(data, null, 2);
    console.log(parsed);
});

it returns this JSON object.

{
  "ip": "118.210.141.127",
  "about": "/about",
  "Pro!": "http://getjsonip.com",
  "reject-fascism": "Women make their own choices. Support abortion rights."
}

For some reason parsed.ip returns undefined, not "118.210.141.127" how do I access the ip value properly?

Upvotes: 0

Views: 230

Answers (2)

sampathsris
sampathsris

Reputation: 22270

Use:

$.getJSON('//jsonip.com/?callback=?', function(data) {
    console.log(data.ip); // should output 118.210.141.127
});

When you call jQuery.getJSON(), the success function will eventually be executed with the parsed JavaScript object, not the JSON string.

So when you do JSON.stringify(data, null, 2), you are converting the JavaScript object back to a JSON string.

Upvotes: 1

Quentin
Quentin

Reputation: 943185

parsed = JSON.stringify(data, null, 2);

JSON.stringify does the oposite of parsing data. It converts a JS data structure into JSON, not the other way around. parsed.ip will then string to read the ip property of a string instead of the parsed object.

getJSON will parse the JSON for you automatically. So just don't mess around with it.

$.getJSON('//jsonip.com/?callback=?', function(data) {
    console.log(data.ip);
});

You might also need to remove ?callback=? from the URL. That is used when you expect a JSONP response, not a JSON response.

Upvotes: 2

Related Questions