Skip to content Skip to sidebar Skip to footer

How To Access JSON Encoded Data Of An Array Using Javascript

How can i access this response from server using javascript. This is the json encoded data. [{'cid':'1234','city':'value1','district':'value2','state':'value3'}] Thanks in

Solution 1:

Assuming the JSON is returned as a string:

var data = '[{"cid":"1234","city":"value1","district":"value2","state":"value3"}]';
// Parse the data as json
var obj = JSON.parse(data)
// Access the ojbect:
console.log(obj);
console.log(obj[0]);     // == Object {cid: "1234", city: "value1", district: "value2", state: "value3"} 
console.log(obj[0].cid); // == 1234

The [0] is to access the first object inside the JSON, which is an array. Then you just add .name, where 'name' is the name of the variable you want. (like .cid).

If the JSON is already a object, you can skip the JSON.parse():

var obj = [{"cid":"1234","city":"value1","district":"value2","state":"value3"}];

And access it like the example above.
(In that case, this question is more about accessing JavaScript objects, instead of JSON)

In your case, you can access the data like this:

success: function (data){
    var obj = JSON.parse(data);
    // Do stuff with `obj` here.
}

Solution 2:

If this is the only response data then you can access as:

var data = [{"cid":"1234","city":"value1","district":"value2","state":"value3"}];
console.log(data[0].cid);

# "1234"

Correction

var data = [{"cid":"1234","city":"value1","district":"value2","state":"value3"}];

var obj = JSON.parse(data);
console.log(obj[0].cid);

# "1234"

Solution 3:

If you recive that response from a page then you can try $.getJSON method using jQuery

$.getJSON("yourwebsite.com/yourpage", function( data ) {
      console.log(data);
});

If you want to use it as a variable, from plain JSON (not accesing to it from another page/request)

var data = '[{"cid":"1234","city":"value1","district":"value2","state":"value3"}]';

Then you can use

$.each( data, function( key, val ) {
          console.log(key + ":" + val);
  });

to access json data in a foreach routine...

Or data[key].innerykey for example data[0].cid 0 is your first array of data, and .cid is the key that you want to retrieve, it can be cid city or whatever you want, if you have more, you can use different number in data[X]


Post a Comment for "How To Access JSON Encoded Data Of An Array Using Javascript"