javascript get nested array elements - javascript

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])

Related

String to JSON Array

I have the below JSON object array which I get back from the server. However while the server sends back the response the data is enclosed in "" and that then makes the javascript function thing this is a String and not an Array.
"[
[32.361346650846805,50.90932315437885],
[32.36743646734031,50.95189517586323],
[32.35467638118774,50.95876163094135],
[32.342494619322636,50.904516635824166],
[32.36279664436138,50.90039676277729],
[32.380194752587755,50.899023471761666],
[32.3648265962154,50.91481631844135],
[32.361346650846805,50.90932315437885]
]"
I just need to get the String into an array and use a for loop to iterate in the set of elements in the array. However since it is being treated a string it is not possible to iterate using a for loop.
any help?
You just need to run this through JSON.parse(), which is supported by almost all the JavaScript parsers:
console.log(JSON.parse(`[
[32.361346650846805,50.90932315437885],
[32.36743646734031,50.95189517586323],
[32.35467638118774,50.95876163094135],
[32.342494619322636,50.904516635824166],
[32.36279664436138,50.90039676277729],
[32.380194752587755,50.899023471761666],
[32.3648265962154,50.91481631844135],
[32.361346650846805,50.90932315437885]
]`));
Just beware that the JavaScript might not like having line-breaks in strings if you give them in source code. If the original string does have line-breaks, that's totally fine. That's why I have used a template literal here.
// Say you have your string here.
var str = `[
[32.361346650846805,50.90932315437885],
[32.36743646734031,50.95189517586323],
[32.35467638118774,50.95876163094135],
[32.342494619322636,50.904516635824166],
[32.36279664436138,50.90039676277729],
[32.380194752587755,50.899023471761666],
[32.3648265962154,50.91481631844135],
[32.361346650846805,50.90932315437885]
]`;
// Convert to array.
var arr = JSON.parse(str);
// Loop throught the array.
for (var i = 0; i < arr.length; i++)
console.log(arr[i]);

Do I have to parse a JSON string and then traverse the resulting object or can I just traverse the string?

I'm learning Google Maps API; a call to its geolocation API returns a giant JSON string (sample: https://maps.googleapis.com/maps/api/geocode/json?address=66+Fort+Washington+Avenue+New+Yor,NY&key=AIzaSyAGLzbjA0rEl5whQgiuZZdIGVzPZzLv9Kg). If I'm looking for a particular key/value pair out of that resulting set of data to use in my Java script application, is it better to convert that JSON string into an object (parse) and then traverse that object for that key/value pair, or is it Ok just to traverse the returned JSON string itself? What are the pros/cons of each?
Parsing the JSON will always result in easier to read code and is less sensitive to changes in the data that you are receiving. However, if you are looking at pure performance it depends on how unique the data is that you are searching for in the returned JSON string, and how many searches you are doing. If you (for instance) just wanted the lat/long location from the returned string you mentioned above then you could do this:
var index = string.search("location");
var index2 = string.substring(index).search(/-?\d/); // finds first number
lat = parseFloat(string.substring(index+index2));
var index3 = string.substring(index+index2).search("lng");
var index4 = string.substring(index+index2+index3).search(/-?\d/); // finds first number
lon = parseFloat(string.substring(index+index2+index3+index4));
Or, by parsing it you could do this:
var obj = JSON.parse(string);
lat = obj.results[0].geometry.bounds.northeast.lat;
lon = obj.results[0].geometry.bounds.northeast.lon;
Clearly the parsed version is easier to read. However, I ran this 200000 times each, and found that the string search based approach was slightly more than 4 times faster than the JSON object parsing approach. There may have been other ways to optimize the search based approach but you get the idea.
You should use JSON.parse to turn your string into a JavaScript object before attempting to access its properties. You cannot "traverse the returned JSON string itself":
var json = '{ "property": "value" }'
// JSON strings cannot be traversed
console.log(typeof json) //=> "string"
console.log(json.property) //=> undefined
var object = JSON.parse(json)
// Objects can be traversed
console.log(typeof object) //=> "object"
console.log(object.property) //=> "value"
If the api is returning json inside an string, you could parse it and just go throught the elements till you find what you need. Otherwise how would you traverse the string? From my point of view, that's something you shouldn't do.

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.

Javascript JSON.parse or directly access

When we can read a property directly from string:
var data = {"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}};
console.log(data.address.streetName); // cde
Why do people use JSON.parse:
var obj = JSON.parse(data);
console.log(obj.address.streetName); // cde
It is not a string, but Javascript object. String is given below
var data = '{"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}}';
to make it object we use JSON.parse
var obj = JSON.parse(data);
console.log(obj.address.streetName); // cde
In your first example, data is an object, but in your second example, data is a JSON string.
That's a major difference. You could call eval(data) to parse a JSON string, but that's very unsafe.
JSON.parse() expects a string. More specifically, a string with a JSON-encoded piece of data.
If it's applied to an object then it's an error, the source of which is probably the common confusion that seems to exist between JavaScript objects and the JSON format.

javascript split and JSON.parse

I want to parse array in JSON format using javascript. I have written following code.
var data = "abc, xyz, pqr";
var data_array = data.split(',');
var data_parsed = JSON.parse(data_array);
alert(data_parsed);
It gives me the error of JSON.parse
I have no idea how to resolve this javascript error.
You don't have any JSON, so don't use JSON.parse. Once you split you already have an array whose elements could be used directly:
var data = "abc, xyz, pqr";
var data_array = data.split(',');
alert(data_array[0]);
and if you want to convert this array to a JSON string you could do this:
var json = JSON.stringify(data_array);
alert(json);
That's because "abc, xyz, pqr" isn't valid JSON. Plus, JSON.parse() is meant to parse JSON strings, not arrays. What are you trying to do, perhaps we can better assist.
This is actually a convenient short cut to json processing if you only need a smaller set of variables.
PHP:
return $var1 .','. $var2 .',some_string_value.';
Javascript:
var myReturnArray = returnValue.split(',');

Categories

Resources