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
Related
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.
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.
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
I am a javascript noob. I have a JSON string created by google gson API after creating the json string which I am passing it to my javascript function. So in a javascript variable I have a string as follows
'{"validationCode":"V10291","caseNumber":"2010CF101011","documentSource":"EFILE","countyDocumentID":"CD102","documentTitle":"D Title","signedDate":"01/01/2012","signedBy":"CPSJC","comments":"YES Comments"}'
How to iterate over this or get a value of the key something like I have to find validationCode or caseNumber, but this is String? Any suggestions are welcome
You can get it into a native JavaScript object with JSON.parse:
var obj = JSON.parse(yourJSONString);
Then you can iterate the keys with a standard for in loop
for(var k in obj)
if ({}.hasOwnProperty.call(obj, k))
console.log(k, " = ", obj[k]);
Or access particular keys like validationCode or caseNumber directly:
var caseNum = obj.caseNumber;
var validationCode = obj.validationCode;
Note that really old browsers don't support JSON.parse, so if you want to support them, you can either use Papa Crockford's json2, or jQuery, which has a parseJSON utility method.
You could do a for ... in to loop through the object properties:
var person={fname:"John",lname:"Doe",age:25};
var x;
for (x in person)
{
document.write(person[x] + " ");
}
http://www.w3schools.com/js/js_loop_for_in.asp
If you are using JQuery framework you can use : jQuery.parseJSON
If not you can use JSON.parse() or you can use eval (which is less safe).
I want to convert below string to an array in javascript.
{a:12, b:c, foo:bar}
How do I convert this string into array of objects? Any cool idea?
I think that the best way of doing this, as Douglas Crockford (one of the biggests gurus of JavaScript) suggests in here is using the JSON native parser, as it is not only faster than the eval(), it's also more secure.
Native JSON parser is already available in:
Firefox 3.5+
IE 8+
Opera 10.5+
Safari Safari 4.0.3+
Chrome (don't know which version)
And Crockford has made a safe fallback in javascript, called json2.js, which is an adaption of the eval() approach, with some security bits added and with the native JSON parsers API. You just need to include that file, remove its first line, and use the native JSON parser, and if it's not present json2 would do the work.
Here is an example:
var myJSONString = '{ "a": 1, "b": 2 }',
myObject = JSON.parse(myJSONString);
Once parsed you'll get an object with attributes a and b, and as you may know, you can treat an object as a hash table or associative array in JavaScript, so you would be able to access the values like this:
myObject['a'];
If you just want a simple array and not an associative one you could do something like:
var myArray = [];
for(var i in myObject) {
myArray.push(myObject[i]);
}
Lastly, although not necessary in plain JavaScript, the JSON spec requires double quoting the key of the members. So the navite parser won't work without it. If I were you I would add it, but if it is not possible use the var myObject = eval( "(" + myString + ")" ); approach.
Since your string is malformed JSON, a JSON parser can't parse it properly and even eval() will throw an error. It's also not an Array but a HashMap or simply an Object literal (malformed). If the Object literal will only contain number and string values (and no child objects/arrays) you can use the following code.
function malformedJSON2Array (tar) {
var arr = [];
tar = tar.replace(/^\{|\}$/g,'').split(',');
for(var i=0,cur,pair;cur=tar[i];i++){
arr[i] = {};
pair = cur.split(':');
arr[i][pair[0]] = /^\d*$/.test(pair[1]) ? +pair[1] : pair[1];
}
return arr;
}
malformedJSON2Array("{a:12, b:c, foo:bar}");
// result -> [{a:12},{b:'c'},{foo:'bar'}]
That code will turn your string into an Array of Objects (plural).
If however you actually wanted a HashMap (Associative Array) and NOT an array, use the following code:
function malformedJSON2Object(tar) {
var obj = {};
tar = tar.replace(/^\{|\}$/g,'').split(',');
for(var i=0,cur,pair;cur=tar[i];i++){
pair = cur.split(':');
obj[pair[0]] = /^\d*$/.test(pair[1]) ? +pair[1] : pair[1];
}
return obj;
}
malformedJSON2Object("{a:12, b:c, foo:bar}");
// result -> {a:12,b:'c',foo:'bar'}
The above code will become a lot more complex when you start nesting objects and arrays. Basically you'd have to rewrite JSON.js and JSON2.js to support malformed JSON.
Also consider the following option, which is still bad I admit, but marginally better then sticking JSON inside an HTML tag's attribute.
<div id="DATA001">bla</div>
<!-- namespacing your data is even better! -->
<script>var DATA001 = {a:12,b:"c",foo:"bar"};</script>
I am assuming you omit quote marks in the string because you had put it inside an HTML tag's attribute and didn't want to escape quotes.
The simplest, but unsafe way to do it is:
eval('(' + myJSONtext + ')')
But since this will interpret any javascript code, it has security holes. To protect against this use a json parser. If you're using a framework (jquery, mootools, etc.) there's a framework-specific call. Most of them are based on Douglas Crawford's parser available at http://www.json.org/js.html.
You can use "for in"
var myObject = {a:'12', b:'c', foo:'bar'};
var myArray = [];
for(key in myObject) {
var value = myObject[key];
myArray[key] = value;
}
myArray['a']; // returns 12
Notes: considering that myObject only have one level of key-value pairs.
JSON.parse will do the trick. Once parsed, you can push them into the array.
var object = JSON.parse(param);
var array = [];
for(var i in object) {
array.push(object[i]);
}
If you're using jQuery, there's the $.parseJSON() function. It throws an exception if the string is malformed, and "Additionally if you pass in nothing, an empty string, null, or undefined, 'null' will be returned from parseJSON. Where the browser provides a native implementation of JSON.parse, jQuery uses it to parse the string"
Use safe evaluation. Unlike JSON.parse, this doesn't require the keys or values to be quoted. Quote values only if they contain embedded commas.
const myStr = "{a:1, b:2, c:3}";
const myObj = string_exp(myStr);
console.log("dot: " + myObj.c);
function string_exp(sCmd) {
return Function(`'use strict'; return (${sCmd})`)();
}
https://dev.to/spukas/everything-wrong-with-javascript-eval-35on#:~:text=the%20variable%20exists.-,Alternatives,-The%20most%20simple