Accessing json data passed in string form - javascript

I am passing data from php in json format, how do I access it?
This is the result:
{"solctype":"Long Term Agreement","checkbox":"1","prnumber":"356363563"}
I have tried
$.post("getgrid?id="+id,
{
},
function(data, status){
console.log(data.solctype);
});
This always returns undefined

You need to parse the string data and convert it to a JavaScript object.
Use something like this:
var stringData = {"solctype":"Long Term Agreement","checkbox":"1","prnumber":"356363563"};
var parsedData = JSON.parse(stringData);
console.log(parsedData.solctype)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Related

Removing root node in json

I have a json data stored in a variable.
var jsonstring;
Json Data:
{ "XYZ": { "abc":[{....}] } }
From above JSON Data, I should not have XYZ node. I need JSON Data as
{ "abc":[{....}] }
How can i remove using Javascript.
If jsonstring is the JSON object, update it
jsonstring = jsonstring["XYZ"]
If jsonstring is a string, do like this.
var json = JSON.parse(jsonstring);
json = json["XYZ"];
If you know the property name you want to remove it's as easy as
json = json.XYZ;
if you don't know it and always want to remove the root note, use
json = json[Object.keys(json)[0]];

getJSON data add array item to variable

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
}
);
}
);`

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

I can't extract JSON array from AJAX request, some return undefined or [object object]

I have mechanism that use AJAX to send-receive data. The data is sent to a php file then when complete the result will be sent back in JSON-from (use encode_json method). Then the json data that received will be extracted for each aim.
The problem appear, when I try to extract the json message that transfered from php file.
This is the Javascript part
function set_filter() {
var a = document.getElementById('Tema');
var b = a.options[a.options.selectedIndex].value;
$.get("filter.php", {tema: b, method: 'set_filter'}, function(data, status) {
alert(status);
console.log(data);
x = JSON.parse(data);
alert(x.count);
});
}
This How result of console.log(data)
Blockquote
{"filters":{"id_filter":["2","1","3"],"judul_filter":["Jenis Arus Dana","Instansi NAD","Kategori Transaksi NAD"]},"select_list":[[["s","p"],["Sumber","Pengeluaran"]],[["1","2","3","4","5","6"],["Bank Sentral","Perbankan","Pemerintah","Domestik Lain","Luar Negeri","Seluruh Instansi"]],[["0200","0300","0400","0500","0600","0700","0800","0900","1000","1010","1020","1021","1022","1023","1024","1025","1030","1100","1200","1210","1220","1230","1300","1400","1410","1420","1500","1800","2000","9000","0100"],["Investasi Non Finansial","Pinjaman Neto","Selisih Statistik","Investasi Finansial Neto","Jumlah Penggunaan Finansial","Jumlah Sumber Finansial","Cadangan Valas Pemerintah","Klaim Dalam Valas Lainnya","Uang Dan Simpanan","Uang Dan Simpanan Dalam Valas","Uang Dan Simpanan Dalam Rupiah","Uang Kertas Dan Logam","Giro","Tabungan","Deposito Berjangka","Simpanan Rupiah Lainnya","Tabungan Giro Pos Dan Koperasi","Surat Berharga Jangka Pendek","Kredit","Kredit Bank Dalam Rupiah","Kredit Institusi Lain D.Rupiah","Kredit Dalam Valas","Modal Saham Dan Penyertaan","Surat Berharga Jangka Panjang","Surat Berharga Pemerintah","Surat Berharga Lainnya","Cadangan Asuransi Dan Pensiun","Kredit Dagang","Rekening Antar Bank","Rupa-Rupa","Tabungan Bruto"]]]}
And when I check this line "alert(x.count);", it's return
Undefined
If I want to extract all judul_filter or id_filter or other, How I can achieve each/specific element ?
NB: I've visit some link such as
Cant read JSON produced by PHP into my javascript
Parse JSON in JavaScript?
Convert JSON string to Javascript array
But from suggestion I try, it returns undefined or [pbject object]. Must the data parse to string using JSON.Stringify(data)? Or How?
-Thanks-
Looks like you are returning a json data, so use the automatic parsing of $.ajax().
You can either use $.getJSON() or pass the data type as 'json' to $.get()
function set_filter() {
var a = document.getElementById('Tema');
var b = a.options[a.options.selectedIndex].value;
$.getJSON("filter.php", {
tema: b,
method: 'set_filter'
}, function (data, status) {
var judul_filter = data.filters.judul_filter;
var id_filter = data.filters.id_filter;
console.log(judul_filter, id_filter);
var select_list = data.select_list;
console.log(data.select_list.length)
});
}
Also there is no property called count in the json, if you want to get the length of an array like select_list use data.select_list.length
You do not have count, you need use x.length

JSON parsing with javascript

I am trying to parse a JSON response from a server using javascript/jquery. This is the string:
{
"status": {
"http_code": 200
},
"contents": "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nDate: Tue, 07 Feb 2012 08:14:38 GMT\r\nServer: localhost\r\n\r\n {\"response\": \"true\"} "
}
I need to get the response value.
Here is what I am trying in the success function of my POST query:
success: function(data) {
var objstring = JSON.stringify(data);
var result = jQuery.parseJSON(JSON.stringify(data));
alert(objstring);
var result1 = jQuery.parseJSON(JSON.stringify(result.contents[0]));
alert(result1.response);
alert(data.contents[0].response);
But so far nothing I have tried returns the correct result' I keep getting undefined, however the contents of objstring are correct and contain the JSON string.
First, set dataType to json. Then data will be an object containing the data specified:
dataType: 'json',
success: function(data) {
alert(data.status.http_code);
alert(data.contents);
}
Read the API for more explanation of what these properties achieve. It would also probably help you to use a Javascript console, so you can use console.log, a much more powerful tool than alert.
Seems like the JSON response itself contains JSON content. Depending on how you call the jQuery.post() method, you'll either get a string or a JSON object. For the first case, use jQuery.parseJSON() to convert the string to a JSON object:
data = jQuery.parseJSON(theAboveMentionedJsonAsString);
Next, get everything inside the contents property after the first \r\n\r\n:
var contentBody = data.contents.split("\r\n\r\n", 2)[1];
Lastly, convert that string to JSON and get the desired value:
var response = jQuery.parseJSON(contentBody).response;
// "true"
try it this way:
var objstring=JSON.stringify(data);
var result=JSON.parse(objstring);
alert("http code:" + result.status.http_code);
alert("contents:" + result.contents);

Categories

Resources