getJSON data add array item to variable - javascript
I am using this script to retrive JSON data from a file to my page.
$.getJSON('json/data.json', function(data) {
$('#getJSON-results').html(JSON.stringify(data));
});
<div id="getJSON-results"></div>
Right now it jsut displays all the data from JSON file as a string on the page.
How would I take the data from my JSON file and place each array into a variable? My data in the JSON file looks like this:
[{"target": "summarize(first, \"1d\", \"sum\")", "datapoints": [[38.393148148148143, 1423958400], [90.800555555555633, 1424044800], [159.06037037037032, 1424131200], [245.5933333333335, 1424217600], [126.94796296296299, 1424304000], [120.37111111111113, 1424390400], [103.04148148148151, 1424476800], [99.273796296296368, 1424563200], [89.38203703703708, 1424649600], [92.970462962963012, 1424736000], [105.62666666666664, 1424822400], [110.33962962962967, 1424908800], [118.54981481481482, 1424995200], [100.08018518518523, 1425081600], [92.52277777777779, 1425168000], [98.647619047618974, 1425254400], [94.585000000000008, 1425340800], [85.568796296296284, 1425427200], [157.82222222222222, 1425513600], [109.7596296296296, 1425600000], [112.53324074074077, 1425686400], [89.392592592592649, 1425772800], [97.253518518518518, 1425859200], [73.424629629629635, 1425945600], [92.377592592592578, 1426032000], [76.117870370370397, 1426118400], [77.83953703703699, 1426204800], [66.643518518518533, 1426291200], [63.748055555555531, 1426377600], [137.30018518518517, 1426464000], [53.480648148148134, 1426550400]]},
{"target": "summarize(second, \"1d\", \"sum\")", "datapoints": [[2.7291600529100535, 1423958400], [5.7797089947089892, 1424044800], [3.4261574074074059, 1424131200], [5.0516335978835958, 1424217600], [6.2272420634920582, 1424304000], [11.752605820105822, 1424390400], [7.8688624338624269, 1424476800], [5.7305555555555525, 1424563200], [5.2784391534391499, 1424649600], [6.4652380952380897, 1424736000], [4.7690277777777741, 1424822400], [4.1451587301587258, 1424908800], [8.4178902116402039, 1424995200], [4.7948611111111061, 1425081600], [4.8153835978835939, 1425168000], [5.3873148148148111, 1425254400], [7.2819378306878262, 1425340800], [5.2084391534391488, 1425427200], [8.098492063492051, 1425513600], [5.6563822751322697, 1425600000], [5.3091468253968195, 1425686400], [4.7850396825396793, 1425772800], [3.8716931216931179, 1425859200], [3.1934325396825369, 1425945600], [3.2083531746031722, 1426032000], [3.3434391534391512, 1426118400], [3.6162235449735438, 1426204800], [3.2094179894179891, 1426291200], [2.3699537037037026, 1426377600], [4.3973544973544945, 1426464000], [2.1901388888888893, 1426550400]]},
{"target": "summarize(third, \"1d\", \"sum\")", "datapoints": [[5.3710185185185182, 1423958400], [11.25367724867724, 1424044800], [8.2990079365079268, 1424131200], [8.710694444444437, 1424217600], [9.6381216931216898, 1424304000], [9.3845105820105807, 1424390400], [9.7305820105820047, 1424476800], [8.6268055555555474, 1424563200], [10.589166666666673, 1424649600], [10.235462962962957, 1424736000], [10.455892857142853, 1424822400], [14.282407407407405, 1424908800], [17.774404761904758, 1424995200], [18.154120370370364, 1425081600], [16.249543650793651, 1425168000], [15.29764550264551, 1425254400], [16.267671957671972, 1425340800], [20.121488095238096, 1425427200], [27.007685185185196, 1425513600], [17.577962962962971, 1425600000], [17.020873015873018, 1425686400], [14.627685185185191, 1425772800], [15.824821428571433, 1425859200], [11.837579365079364, 1425945600], [13.292539682539683, 1426032000], [12.064074074074073, 1426118400], [12.279457671957676, 1426204800], [9.3799074074073978, 1426291200], [7.8777314814814732, 1426377600], [13.161825396825407, 1426464000], [7.2587499999999956, 1426550400]]}]
I am new to using JSON and would also appreciate any advice on the approach I'm taking.
How can I now make this data accsessable outside the getJSON?
$.getJSON('json/data.json', function(data) {
yourData = data;
makeMeGlobal = yourData[0];
});
console.log(makeMeGlobal.datapoints);
Changing your function to the following will result in an object you can then reference normally:
$.getJSON('json/data.json', function(data) {
yourData = data;
});
You could then get the first set of datapoints like this:
yourData.datapoints[0]
Should be:
data.forEach(function (obj) {
// obj now has each JSON object in this array
var test = obj.target;
}
When you get a JSON from AJAX, it's already ready for use in the browser. This is one of the nice perks of using JSON over XML.
It's already an array, because the original JSON string was parsed by jQuery. If you use stringify, you will get a string which contains the JSON representing the array (not useful for your purposes, as it's the same string returned by the server).
For example:
$.getJSON('json/data.json', function(data) {
// Here, data is already an array.
var data_length = data.length;
for (var i = 0; i < data_length; i++) {
var obj = data[i]; // Here we have an object from the array
alert("I have an object which target is " + obj.target);
}
});
You need to iterate through json to retrieve the value you need and append the html.More infor # https://stackoverflow.com/a/18238241/909535 Something like this
`$.getJSON('json/data.json', function(data){
data.forEach(
function(val, index, array) {
//val.target will have target attribute's value
//val.datapoints is a array which you can iterate
}
);
}
);`
Related
Parse Json result and isolate specific values
This is my returned JSON: { //... "results":[ { //more properties... "geometry":{ "lat":51.2244644, "lng":0.7334215 } }, //more results... ], //... } Complete JSON I want to get information from a json result returned without having to use a specific companies JS helper file, just using the pure result myself. I'm looking to isolate results lat and lng shown here: "geometry":{ "lat":51.2244644, "lng":0.7334215 } It seems like I can use code similar to this to get my result: var json = '{"result":true,"count":1}', obj = JSON.parse(json); alert(obj.count); How can I get the first coordinates returned in the result so I can later store them in an input box? I don't mind using jQuery if it simplifies this.
You can get first coordinates like following. var json = '{"results":[{"geometry":{"lat":51.2244644,"lng":0.7334215}}]}'; var first_coordinate = JSON.parse(json).results[0].geometry; console.log(first_coordinate); If you want to get all coordinates in an array then try like following. var arr = $(JSON.parse(json).results).map(function () { return this.geometry; }).get(); console.log(arr);
USE like this after JSON parsing co-ordiniates from DMS myArray.results[0].annotations.DMS co-ordinitates from gemotery myArray.results[0].geometry You need to loop the results to get all co-ordinates
JavaScript, JSON, referencing by name
How do you reference a JSON object in JavaScript? I have a JSON response from a Rest web service and trying to reference the contents of the response which I have parsed to JSON by way JSON.Parse(response) Sample JSON: { "HotelListResponse":{ "customerSessionId":"", "numberOfRoomsRequested":1, "moreResultsAvailable":true, "cacheKey":"", "cacheLocation":"", "cachedSupplierResponse":{ "#supplierCacheTolerance":"NOT_SUPPORTED", "#cachedTime":"0", "#supplierRequestNum":"101", "#supplierResponseNum":"", "#supplierResponseTime":"", "#candidatePreptime":"14", "#otherOverheadTime":"", "#tpidUsed":"", "#matchedCurrency":"true", "#matchedLocale":"true" }, "HotelList":{ "#size":"20", "#activePropertyCount":"101", "HotelSummary":[ { "name":"name1" }, { "name":"name2" } ] } } } How can I, for example reference the customerSessionId? And the second HotelSummary name? For customerSessionId I have tried jsonObject.customerSessionId which returns undefined. For the second hotel summary name I have tried jsobObject.HotelList.HotelSummary[1].name which is undefined too.
Given the JSON string above parsed and assigned to a variable as such: var response = JSON.Parse(jsonString); you should be able to access it like this: var customerSessionId = response.HotelListResponse.customerSessionId;
Here's the working solution fiddle As you can see, you need to reference HotelListResponse, so if your var result holds your json object, then you can fetch the values by using var first = result.HotelListResponse.customerSessionId var second = result.HotelListResponse.HotelList.HotelSummary[1].name
extract single variable from JSON array
I hope my question is not as stupid as I think it is... I want to extract (the value of) a single variable from an JSONarray. I have this jquery code $(document).ready(function(){ $("#gb_form").submit(function(e){ e.preventDefault(); $.post("guestbook1.php",$("#gb_form").serialize(),function(data){ if(data !== false) { var entry = data; $('.entries').prepend(entry); } }); }); }); the content of data looks like this ("MyMessage" and "MyName" are values written in a simple form from user): [{"message":"MyMessage","name":"MyName"}] the var "entry" should give (more or less) following output at the end: "Send from -MyName- : -MyMessage-" I'm not able to extract the single array values from data. I tried things like that: var message = data['message']; var name = data['name'] var entry = "Send from" + name + ":" +message; but that gives "Send from undefined: undefined" Hope you can help me with that.
you can do like this to get first item of array: var msg = "Send from"+data[0].name + " "+data[0].message; console.log(msg ); SAMPLE FIDDLE UPDATE: as you are using $.post you will need to explicitly parse response as json: $.post("guestbook1.php",$("#gb_form").serialize(),function(data){ var response = jQuery.parseJSON(data); var msg = "Send from"+response [0].name + " "+response [0].message; console.log(msg ); });
To access an array you use the [] notation To access an object you use the . notation So in case of [{JSON_OBJECT}, {JSON_OBJECT}] if we have the above array of JSON objects in a variable called data, you will first need to access a particular Json Object in the array: data[0] // First JSON Object in array data[1] // Second JSON Object in array.. and so on Then to access the properties of the JSON Object we need to do it like so: data[0].name // Will return the value of the `name` property from the first JSON Object inside the data array data[1].name // Will return the value of the `name` property from the second JSON Object inside the data array
How to parse dynamic json data?
I am using wikipedia API my json response looks like, "{ "query": { "normalized": [ { "from": "bitcoin", "to": "Bitcoin" } ], "pages": { "28249265": { "pageid": 28249265, "ns": 0, "title": "Bitcoin", "extract": "<p><b>Bitcoin</b>isapeer-to-peerpaymentsystemintroducedasopensourcesoftwarein2009.Thedigitalcurrencycreatedandlikeacentralbank, andthishasledtheUSTreasurytocallbitcoinadecentralizedcurrency....</p>" } } } }" this response is coming inside XMLHTTPObject ( request.responseText ) I am using eval to convert above string into json object as below, var jsonObject = eval('(' +req.responseText+ ')'); In the response, pages element will have dynamic number for the key-value pair as shown in above example ( "28249265" ) How can I get extract element from above json object if my pageId is different for different results. Please note, parsing is not actual problem here, If Parse it , I can acess extract as, var data = jsonObject.query.pages.28249265.extract; In above line 28249265 is dynamic, This will be something different for different query
assuming that u want to traverse all keys in "jsonObject.query.pages". u can extract it like this: var pages = jsonObject.query.pages; for (k in pages) { // here k represents the page no i.e. 28249265 var data = pages[k].extract; // what u wana do with data here } or u may first extract all page data in array. var datas = []; var pages = jsonObject.query.pages; for (k in pages) { datas.push(pages[k].extract); } // what u wana do with data array here
you can archive that using two methods obj = JSON.parse(json) OR obj = $.parseJSON(json); UPDATE Try this this var obj = JSON.parse("your json data string"); //console.log(obj) jQuery.each(obj.query.pages,function(a,val){ // here you can get data dynamically var data = val.extract; alert(val.extract); }); JSBIN Example JSBIN
How to Access Array response of AJAX
This is my AJAX call response which is in array format [1,2,3,4,5,6] success: function(outputfromserver) { $.each(outputfromserver, function(index, el) { }); How can we access outputfromserver all values ?? Means outputfromserver Zeroth value is 1 , 2nd element is 2 , -----so on
It would help to know what your AJAX request looks like. I recommend using $.ajax() and specifying the dataType as JSON, or using $.getJSON(). Here is an example that demonstrates $.ajax() and shows you how to access the returned values in an array. $.ajax({ url: 'test.json', // returns "[1,2,3,4,5,6]" dataType: 'json', // jQuery will parse the response as JSON success: function (outputfromserver) { // outputfromserver is an array in this case // just access it like one alert(outputfromserver[0]); // alert the 0th value // let's iterate through the returned values // for loops are good for that, $.each() is fine too // but unnecessary here for (var i = 0; i < outputfromserver.length; i++) { // outputfromserver[i] can be used to get each value } } }); Now, if you insist on using $.each, the following will work for the success option. success: function (outputfromserver) { $.each(outputfromserver, function(index, el) { // index is your 0-based array index // el is your value // for example alert("element at " + index + ": " + el); // will alert each value }); } Feel free to ask any questions!
The array is a valid JSON string, you need to parse it using JSON parser. success: function(outputfromserver) { var data = JSON.parse(outputfromserver); $.each(data, function(index, el) { // Do your stuff }); }, ...
You can use JS objects like arrays For example this way: // Loop through all values in outputfromserver for (var index in outputfromserver) { // Show value in alert dialog: alert( outputfromserver[index] ); } This way you can get values at first dimension of array, above for..loop will get values like this: // Sample values in array, case: Indexed array outputfromserver[0]; outputfromserver[1]; outputfromserver[2]; // So on until end of world... or end of array.. whichever comes first. outputfromserver[...]; However, when implemented this way, by using for ( index in array ) we not only grab indexed 1,2,3,4,... keys but also values associated with named index: // Sample values in array, case: accosiated/mixed array outputfromserver["name"]; outputfromserver["phone"]; outputfromserver[37]; outputfromserver[37]; outputfromserver["myindex"]; // So on until end of world... or end of array.. whichever comes first. outputfromserver[...]; In short, array can contain indexed values and/or name associated values, that does not matter, every value in array is still processed. If you are using multidimensional stuff then you can add nested for (...) loops or make recursive function to loop through all and every value. Multidimensional will be something like this: // Sample values in array, case: indexed multidimensional array outputfromserver[0][0]; outputfromserver[0][1]; outputfromserver[1][0]; outputfromserver[1][...]; outputfromserver[...][...]; Update, JSON object: If you server returns JSON encoded string you can convert it to javascript object this way: try { // Try to convert JSON string with jQuery: serveroutputobject = $.parseJSON(outputfromserver); } catch (e) { // Conversion failed, result is not JSON encoded string serveroutputobject = null; } // Check if object converted successfully: if ( serveroutputobject !== null ) { // Loop through all values in outputfromserver for (var index in serveroutputobject) { // Append value inside <div id="results">: $('#results').append( serveroutputobject[index] + "<br/>" ); } } // In my own projects I also use this part if server can return normal text too: // This way if server returned array we parse it and if server returns text we display it. else { $('#results').html( outputfromserver ); } More information here
$.ajax({ type : "POST", dataType: "json", url : url, data:dataString, success: function(return_data,textStatus) { temperature.innerText=return_data.temp; // OR **temperature.innerText=return_data['temp'];** }, error: function(jqXHR, textStatus, errorThrown) { alert("Error while accessing api [ "+url+"<br>"+textStatus+","+errorThrown+" ]"); return false; } });