简体   繁体   中英

How to get value from json object using jquery?

I have the following ajax call and the json feed it returns. how do I get the value of the data object ie FRI from the feed using jquery?

$.ajax({
    url: query,
    type: "GET",
    dataType: "json"
    success: function(data) {
        var day = // get data value from json
        $("#Day").val(day);
    }
});    

{
   "name":"workdays",
   "columns":[
      "day"
   ],
   "data":[
      [
         "FRI"
      ]
   ]
}     

* update *

What would be the syntax be if the results were returned as jsonp as follows, how can you extract the value 'FRI' :

import({
  "Results":{
    "work_days":{
        "empid":100010918994,
        "day":"FRI"
     }
  }
});

This is just JavaScript, not jQuery.

var data = {
   "name":"workdays",
   "columns":[
      "day"
   ],
   "data":[
      [
         "FRI"
      ]
   ]
}

data.data[0][0]; //FRI

UPDATE

var obj = {
  "Results":{
    "work_days":{
        "empid":100010918994,
        "day":"FRI"
     }
  }
}

obj.Results.work_days.day //FRI

If the latter json is the json you get from the server, you can get the data like this:

var day = data.data[0][0];

This will put the value FRI in the variable day .

EDIT: If you use a recent browser, you can always do console.log(data) and look in your javascript console what is in the variable

    $.ajax({
    url: query,
    type: "GET",
    dataType: "json"
    success: function(data) {
        var day = data.data[0][0] // get data value from json
        $("#Day").val(day);
    }
});    

{
   "name":"workdays",
   "columns":[
      "day"
   ],
   "data":[
      [
         "FRI"
      ]
   ]
} 

json is javascript object, so you can access to any his property:

data.name
data.columns
data.data

You don't need jquery data is a javascript object (hash). You can access the data as follow:

data.columns

Or

data["columns"]

For retrieving the 'data' field

$.ajax({
url: query,
type: "GET",
dataType: "json"
success: function(data) {
    var day = data['data']; // get data value from json
    $("#Day").val(day);
}
});    

{
   "name":"workdays",
   "columns":[
   "day"
],
"data":[
   [
     "FRI"
   ]
]
} 

Have you ever checked the data.d variable?

success: function(data) {
   console.log(data.d); //prints the value
}

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