extract single variable from JSON array - javascript

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

Related

JQuery - How to loop through JSON using each

I have cached the JSON returned from an Ajax call and need to loop through this to display it. I get the error, 'Cannot read property 'title' of undefined'. Can anyone help?
$.each(cache['cat-'+cat], function(i, jd) {
var title= jd.title; //issue is here
)}
When I console.log(cache['cat-'+cat]) I get the below:
Object {
date: "2016-07-28T15:08:03.596Z",
data: '[{"id":471,"title":"Lines and Calls","solution_areas":"lines-calls"}]'
}
When I console.log(jd) within the loop I get the below:
2016-07-28T15:13:14.553Z
if I use console.log(jd.data); I get
undefined
I have tried the below but they don't work either:
var title= jd.data.title;
var title= jd.data[0].title;
Can anyone tell me what I am doing wrong?
The way you are currently using it, each is going to iterate over every property of the cache['cat-'+cat] object, of which there are two, date and data.
So your anonymous function function(i, jd)will be called twice. The first time, jdwill be the value of the date property (a string), the second time it will be the value of the data property (also a string, that happens to be formatted as JSON).
The contents of data need to be parsed before they can be accessed as an object/array, and given that data is formatted as an array, I am guessing that you actually want to iterate over that. Given the example provided, I would change it to:
$.each(JSON.parse(cache['cat-'+cat].data), function(i, jd) {
var title= jd.title;
});
You aren't accessing it properly. And since cache['cat-'+cat] is already the needed object, what's the purpose of $.each? Should be
var title= JSON.parse(cache['cat-'+cat].data)[0].title;
(because the title is in the data, and the data is JSON).
Demo:
var obj = {
date: "2016-07-28T15:08:03.596Z",
data: '[{"id":471,"title":"Lines and Calls","solution_areas":"lines-calls"}]'
};
var title= JSON.parse(obj.data)[0].title;
console.log(title);
Just need to understand what is JSON and what is STRING
cache['cat-'+cat].data return a string that need to convert to JSON before pass to each loop:
var dataCacheReturned = cache['cat-'+cat];
var objCache = dataCacheReturned.data; //Its return a string
objCache = JSON.parse(objCache); //Parse string to json
$.each(objCache, function(i, jd) {
var title = jd.title;
console.log(title);
});

How to To Delete The data in Localstorage

what I need
I need to toggle image on click.
like if user select favorite choice & then it mark unfavorite image is altered and data is deleted from localstoarge.
html code
<div style="display:block; float:right; width:auto; color:#7c7c7c;">
</div>
js code
function favaorite(sess_id,name,city,country,event_url,pointer){
var eventData;
//is anything in localstorage?
if (localStorage.getItem('eventData') === null) {
eventData = [];
} else {
// Parse the serialized data back into an array of objects
eventData = JSON.parse(localStorage.getItem('eventData'));
//alert(eventData);
$.each(eventData, function(key, value){
//console.log(value);
var imageUrl='http://im.gifbt.com/images/star1_phonehover.png';
//var imageUrl='http://im.gifbt.com/images/star1_phone.png';
$(pointer).closest('.evt_date').find('.favourate_dextop').css('background-image', 'url("' + imageUrl + '")');
//$(pointer).closest('.evt_date').find('.favourate_dextop').css('background-image', 'url("' + imageUrl + '")');
});
}
var details={};
details.sess_id=sess_id;
details.name=name;
details.city=city;
details.country=country;
details.event_url=event_url;
// Push the new data (whether it be an object or anything else) onto the array
eventData.push(details);
// Alert the array value
//alert(eventData); // Should be something like [Object array]
// Re-serialize the array back into a string and store it in localStorage
var jsondata=localStorage.setItem('eventData', JSON.stringify(eventData));
}
problem
I'm new in localstorage I need to know how could I delete data from json string.
I have implemented add to favorite now I need to mark unfavorite.
data is stored:
[{
"sess_id":182104,
"name":"AUTOMECH FORMULA",
"city":"Cairo",
"country":"Egypt",
"event_url":"automech-formula"
},]
To delete data from localstorage you use localStorage.removeItem('itemNam')
example
localStorage.setItem('name','hello');
to delete the name item from the localStorage you use
localStorage.removeItem('name');
BUT IF YOUR QUESTION IS HOW TO DELETE DATA FROM JSON OBJECT THEN YOU HAVE TWO METHODS
1: changing the original json object
delete originalJson.attributeName
originalJson = {name:'myname',age:30};//our object to test with
example :
delete originalJson.age //in this case originalJson.age is no more available
2: don't change the original object and make another copy instead
originalJson2 = JSON.stringify(originalJson);
originalJson2 = JSON.parse(originalJson2);
delete originalJson2.age //originalJson.age is available but originalJson2.age is not available
here is the : jsfiddle
let assume that sess_id is your unique id for events
function unfavorite(sess_id){
var eventData = localStorage.getItem('eventData');
//is anything in localstorage?
if (localStorage.getItem('eventData') === null) {
console.log('invalid event');
}
eventData = JSON.parse(eventData);
// Keep all without the one with specified sess_id
$.grep(eventData, function(value) {
return value.sess_id != sess_id;
});
var jsondata=localStorage.setItem('eventData', JSON.stringify(eventData));
}

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

Javascript [Object object] error in for loop while appending string

I am a novice trying to deserialize my result from an onSuccess function as :
"onResultHttpService": function (result, properties) {
var json_str = Sys.Serialization.JavaScriptSerializer.deserialize(result);
var data = [];
var categoryField = properties.PodAttributes.categoryField;
var valueField = properties.PodAttributes.valueField;
for (var i in json_str) {
var serie = new Array(json_str[i] + '.' + categoryField, json_str[i] + '.' + valueField);
data.push(serie);
}
The JSON in result looks like this:
[
{
"Text": "INDIRECT GOODS AND SERVICES",
"Spend": 577946097.51
},
{
"Text": "LOGISTICS",
"Spend": 242563225.05
}
]
As you can see i am appending the string in for loop..The reason i am doing is because the property names keep on changing therefore i cannot just write it as
var serie = new Array(json_str[i].propName, json_str[i].propValue);
I need to pass the data (array type) to bind a highchart columnchart. But the when i check the var serie it shows as
serie[0] = [object Object].Text
serie[1] = [object Object].Spend
Why do i not get the actual content getting populated inside the array?
You're getting that because json_str[i] is an object, and that's what happens when you coerce an object into a string (unless the object implements toString in a useful way, which this one clearly doesn't). You haven't shown the JSON you're deserializing...
Now that you've posted the JSON, we can see that it's an array containing two objects, each of which has a Text and Spend property. So in your loop, json_str[i].Text will refer to the Text property. If you want to retrieve that property using the name in categoryField, you can do that via json_str[i][categoryField].
I don't know what you want to end up with in serie, but if you want it to be a two-slot array where the first contains the value of the category field and the second contains the value of the spend field, then
var serie = [json_str[i][categoryField], json_str[i][valueField]];
(There's almost never a reason to use new Array, just use array literals — [...] — instead.)

Categories

Resources