iterate json element received from php - javascript

I have some info in JSON which is coming from PHP via Ajax
{"5":"rahul","26":"karan","28":"jatin"}
I wants to get key separate which are 5,26,28
and separate name which are rahul,karan,jatin
I use this code in java script. But doesn't get result as i want.
for (var key in ajaxresponse) {
if (ajaxresponse.hasOwnProperty(key))
{
alert(key + " -> " + JSON.stringify(ajaxresponse[key]));
}
}

On a really simple level, the for() is using ajaxresponse and the if/alert are using response.
If the code you've pasted the actual code? If so, that could be your problem. :)

Simply use 2 arrays, to get to what you want:
var keys = [], vals = [], key,
ajaxresponse = JSON.parse(ajaxresponse);//parse JSON, which is quite important, too!
for (key in ajaxresponse)
{
if (ajaxresponse.hasOwnProperty(key))
{
keys.push(key);
vals.push(ajaxresponse[key]);
console.log(key + '->' + ajaxresponse[key]);//no need to call JSON.stringify on a string
}
}
console.log(keys.join(', '));//will list all keys, comma-separated
console.log(vals.join(', '));//ditto for values

follow this post to iterate your json data with the help of jQuery
iterate using jQuery

Related

Adding an Individual JSON Object to an Array to Parse and Process

I have the following json object samples, i.e.:
{"id":"value1" , "time":"valuetime1"}
{"id":"value2" , "time":"valuetime2"}
{"id":"value3" , "time":"valuetime3"}
{"id":"value4" , "time":"valuetime4"}
{"id":"value5" , "time":"valuetime5"}
{"id":"value6" , "time":"valuetime6"}
{"id":"value7" , "time":"valuetime7"}
{"id":"value8" , "time":"valuetime8"}
Based on the above, I would like to add all these json objects to an array, where I can then process and access the array for each json object and extract id1 value together with time1 value and so forth.
I believe I have to use JSON.parse but unsure of how to firstly add these objects to an array and then be able to also parse and access each object's data.
Think of each row above as a separate JSON object which I would like added to an array that is parsed.
Read the file line by line (each line is a separate json)
Parse the line json text to JavaScript object
Put/push/append JavaScript object into a JavaScript array
This is not valid JSON, so JSON.parse would not work, but assuming you have the text in a string variable, you can convert it to JSON with something like:
data = "[" + data.replace(/\}/g, "},").replace(/,$/,"") + "]";
and then parse it.
UPDATE:
var array = [];
// for each input line
var obj = JSON.parse(line);
array.push(obj);
var id = obj.id;
var time = obj.time;
...
Appreciate the responses but I believe I have managed to solve my own question.
Furthermore, as #Mr. White mentioned above, I did have my property names in error which I have now sorted - thanks.
Using the data above, all I was after was the following:
UPDATED
var s = '{"id":"value1","time":"valuetime1"},{"id":"value2","time":"valuetime2"},{"id":"value3","time":"valuetime3"},{"id":"value4","time":"valuetime4"},{"id":"value5","time":"valuetime5"}, {"id":"value6","time":"valuetime6"},{"id":"value7","time":"valuetime7"},{"id":"value8","time":"valuetime8"}';
var a = JSON.parse('[' + s + ']');
a.forEach(function(item,i){
console.log(item.id + ' - '+ item.time);
});
Thanks for the heads up #torazaburo - have updated my answer which I should've done much earlier.

convert java map to javascript map and loop over to get keys/values?

In java i have hashmap
Map<String , List<Employee>> employeeMap = new HashMap<String , List<Employee>> ();
employeeMap.put(1, new Employee());
........
I am adding it in request attribute
Now in javascript i need to loop over over map, to get keys and values
Here what i tried
Approach 1 :-
var empMap = '${employeeMap}';
//here is the example value of map in javascript which i see while debugging
//var empMap = {emp1_100=[com.Employee#5b7b4bc5], emp2...
for (var key in empMap) {
alert(key + ': ' + empMap[key]);
}
But getting syntax error
SyntaxError: missing : after property id
Approach 2 :- with jquery
var jsonMap = $.stringify(empMap);
$.each( jsonMap, function( key, value ) {
alert( key + ": " + value );
});
But its not working either. It print some characters.
I am not sure what i am missing here ?
Looks like you are simply writing whatever the .toString() method of your Map returns to the request, which is not a good idea in the first place.
If I were you, I would convert your Map into a JSON object (there various ways to do that, depending on your system) and then append the String representation of this JSON object to the request, because then you can simply call "JSON.parse( ... );" in JavaScript to transform it into a JavaScript object without having to do any parsing yourself.

Concatenate json arrays from localStorage and send to PHP

I am using localStorage to store some json arrays (no more than 25), and when the user logs out, I need to save the information stored in a MySQL database. Therefore, I am sending the data to a PHP script that is in charge of communicating and dealing with all the database stuff.
Anyway, I have been searching on the web, and I found here - Merge two json/javascript arrays in to one array - that I could just use concat.
I basically use this function:
function saveEverything() {
var localStorageData = "";
for (var i=0; i < localStorage.length; i++) {
localStorageData = localStorageData.concat(localStorage.getItem(localStorage.key(i)));
}
...
}
The ... represents the ajax bit that sends the localStorageData to a PHP script.
As you should know, localStorage doesn't store anything but strings, so I have to do JSON.stringify when I am setting the items. You might have noticed that I didn't do JSON.parse when concatenating the localStorage items into the localStorageData variable. I tried that before, and when I did alert(localStorageData) I only got [Object][object] ... (or something like that).
Anyway, with this kind of approach I am sending strings to php, and each json array is separated by line break. Is this the best/correct thing to do or should I have sticked to the JSON.parse way?
What does your JSON look like? concat is a method of Array instances, so you can only do this when you're working with an Array. Furthermore, JSON is a notation, to use it like this you would have to parse it back into JavaScript and then out again.
For example,
var json1 = '[{"foo":"bar"}]',
json2 = '[{"fizz":"buzz"}]';
var mergedJS = JSON.parse(json1).concat(JSON.parse(json2)),
mergedJSON = JSON.stringify(merged);
mergedJSON; // '[{"foo":"bar"},{"fizz":"buzz"}]'
If they're not Arrays, you might be able to get away with just wrapping them (depending on how you want the result), i.e.
var json1 = '{"foo":"bar"}',
json2 = '{"fizz":"buzz"}';
var mergedJSON = '[' + json1 + ',' + json2 + ']';
mergedJSON; // '[{"foo":"bar"},{"fizz":"buzz"}]'
Finally,
You might have noticed that I didn't do JSON.parse when concatenating the localStorage items into the localStorageData variable. I tried that before, and when I did alert(localStorageData) I only got [object Object]
[object Object] is the result of calling toString on almost any Object.
({}).toString(); // "[object Object]"
If you want to see something useful, use console.log and view the Console, or convert back to String with JSON.stringify.
alert(localStorageData) I only got [Object][object]
That's normal, you should stick with this previous version, build an object of objects and in the end use
JSON.stringify(localStorageData)
to send it as string.
function saveEverything(){
var localStorageData = {},
l = localStorage.length,
k;
for (var i=0; i < l; i++) {
k = localStorage.key(i);
localStorageData[k] = JSON.parse(localStorage.getItem(k));
}
return localStorageData;
}
Using object also makes it easier to distinguish these arrays, since you can also save keys under which they were saved.

Deserializing the result of jQuery.Serialize (to an array - not to a form)

Is it possible to deserialize the result of jQuery.Serialize to an array (or other similar JavaScript data structure)?
I know about the jQuery.Deserialize plugin but I don't think you can get the deserialized data; i.e., it is for deserializing back to the original form (from which you previously serialized the data).
If You want it as an array , try using serializeArray instead of serialize, that gives you the elements mapped to their names as an associative array.
.serializeArray()
As #SpiXel has shown you can use serializeArray to generate an array from a <form> element.
There is no function available in jQuery to convert the string generated by serialize function. You have to do something as shown below
var paramString = $("#cform").serialize();
var jsonString = '{"' + paramString.replace(/[&=]/g, function(a, b) {
return (a == "&" ? ",\"" : "\":");
}) + '}';
var object = $.parseJSON(jsonString);
Try using this syntax, Hope It will help you.
var d = $('#form4').serializeArray();
d.push({lead_id : $("#lead_id").val()});

help looping a JSON object

Hi
after a query in php and converting the results to JSON with json_encode i have this:
{"ga:visits":"59","ga:pageviews":"117","ga:timeOnSite":"4775.0","average_time_on_site_formatted":"0:01:20","pages_per_visit":"1.98"}
my problem is how to loop it and store the keys and values in different variables.
i`m not a javascript guy so please help and give good details.
best regards
You need to parse the JSON-string into a Javascript object first. Most browser nowadays have a native support for that in window.JSON.
var myObj = JSON.parse('{"ga:visits":"59","ga:pageviews":"117","ga:timeOnSite":"4775.0","average_time_on_site_formatted":"0:01:20","pages_per_visit":"1.98"}');
After that, you can just loop over the keys:
for(var key in myObj) {
console.log(key, ' is: ', myObj[key]);
}
If you want to use that in "old'ish" browsers, like IE7 and below you need to use the json2.js from http://www.json.org to have the same functionality.
var parsedObject = JSON.parse(str); //str - json string in your example
for(var key in parsedObject){
// to access each key name - use "key"
// to acces each value use parsedObject[key]
document.writeln("key:" + key + "; value: " + parsedObject[key]);
}
I would suggest evaluating it with something like
var obj = eval(jsonString);
this will turn the entire string into an object with fields:
ga:visits
ga:pageviews
ga:timeOnSite
etc.
Then go you can access each variable by name, like obj.pages_per_visit

Categories

Resources