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).
Related
I have String like below.
10=150~Jude|120~John|100~Paul#20=150~Jude|440~Niroshan#15=111~Eminem|2123~Sarah
I need a way to retrieve the string by giving the ID.
E.g.: I give 20; return 150~Jude|440~Niroshan.
I think I need a HashMap to achieve this.
Key > 20
Value > 150~Jude|440~Niroshan
I am looking for an pure JavaScript approach. Any Help greatly appreciated.
If you're getting the above string in response from server, it'll be better if you can get it in the below object format in the JSON format. If you don't have control on how you're getting response you can use string and array methods to convert the string to object.
Creating an object is better choice in your case.
Split the string by # symbol
Loop over all the substrings from splitted array
In each iteration, again split the string by = symbol to get the key and value
Add key-value pair in the object
To get the value from object using key use array subscript notation e.g. myObj[name]
var str = '10=150~Jude|120~John|100~Paul#20=150~Jude|440~Niroshan#15=111~Eminem|2123~Sarah';
var hashMap = {}; // Declare empty object
// Split by # symbol and iterate over each item from array
str.split('#').forEach(function(e) {
var arr = e.split('=');
hashMap[arr[0]] = arr[1]; // Add key value in the object
});
console.log(hashMap);
document.write(hashMap[20]); // To access the value using key
If you have access to ES6 features, you might consider using Map built-in object, which will give you helpful methods to retrieve/set/... entries (etc.) out-of-the-box.
in javascript how do I get individual elements out of this array?
http://pastebin.com/n8yrnCpf
I need to loop through it and format the data
how would I get array[0][1][1], for instance
and perhaps there is some json script for doing it quickly
Json comes from J ava S cript O bject N otation. It's a javascript-compatible format, so you can loop through it, and access it as you need. In other words, you do can get array[0][1][1].
If what you're asking for is how can you receive a JSON in a string and convert it to an "usable" JavaScript variable, you can do that this way:
var json_string = "[[['whatever','and'],['more','whatever']]]"
var parsed_json = JSON.parse (json_string)
console.log (parsed_json[0][0])
Or, if you use old browsers (IE7 and so), you can use JQuery and its elder-safe function parseJSON:
var json_string = "[[['whatever','and'],['more','whatever']]]"
var parsed_json = $.parseJSON (json_string)
console.log (parsed_json[0][0])
I have a string: items[0].name that I want to apply to a JSON object: {"items":[{"name":"test"}]} which is contained in the variable test. I want to apply that string to the object in order to search it (test.items[0].name). I can only think of one way to do this: parse the square brackets and dots using my own function. Is there another way I can do this? Perhaps using eval? (Even though I'd LOVE to avoid that...)
For clarity:
I have a JSON object, what is inside of it is really irrelevant. I need to be able to query the object like so: theobject.items[0], this is normal behaviour of a JSON object obviously. The issue is, that query string (ie. items[0]) is unknown - call it user input if you like - it is literally a string (var thisIsAString = "items[0]"). So, I need a way to append that query string to theobject in order for it to return the value at theobject.items[0]
function locate(obj, path) {
path = path.split('.');
var arrayPattern = /(.+)\[(\d+)\]/;
for (var i = 0; i < path.length; i++) {
var match = arrayPattern.exec(path[i]);
if (match) {
obj = obj[match[1]][parseInt(match[2])];
} else {
obj = obj[path[i]];
}
}
return obj;
}
var name = locate(test, 'items[0].name');
...JSON doesn't have objects, it's just a string.
If you're dealing with an object (ie: you can reference it using dot/bracket notation) then it's just a JavaScript object/array...
So depending on what the deal is, if you're dealing with a 100% string:
'{"name":"string","array":[0,1,2]}'
Then you need to send it through JSON.parse;
var json_string = '{"name":"string","array":[0,1,2]}',
js_obj = JSON.parse(json_string);
js_obj.name; // "string"
js_obj.array; // [0,1,2]
js_obj.array[1]; // 1
If it's not a string, and is indeed an object/array, with other objects/arrays inside, then you just need to go:
myObj.items[0].name = items[0].name;
If it IS a string, then .parse it, and use the parsed object to do exactly what I just did.
If it needs to be a string again, to send to the server, then use JSON.stringify like:
var json_string = JSON.stringify(js_obj);
Now you've got your modified JSON string back.
If you need to support GhettoIE (IE < 8), then download json2.js from Douglas Crockford, and add that script on the page conditionally, if you can't find window.JSON.
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
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