Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access JSON encoded data of an array using javascript

Tags:

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 advance.

This is the ajax code:

 function cityauto(ctid){
     var city = document.getElementById(ctid);
     if(city.value.length > 3){
         $.ajax({
             type: "GET",
             url: "city.php",
             data: {term: city.value},
             success: function (data){
                 alert(data);
             }
         });
 }

Html code:

   <input type="text" name="city" id="cty" onblur="cityauto(this.id);" />

onblur i am getting above response from php file in alert box now i need to access that values in javscript.

like image 358
NiksD Avatar asked Jan 10 '14 09:01

NiksD


2 Answers

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.
}
like image 168
Cerbrus Avatar answered Oct 02 '22 13:10

Cerbrus


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"
like image 23
brg Avatar answered Oct 02 '22 13:10

brg