JavaScript: How to convert a string to a 2D array - javascript

I have a String value as input that contains a 2-dimensional array in the following format:
"[[1,0,1,1],[0,1,0,1],[1,0,1,1],[0,1,0,1]]"
Also, I need to build the actual multidimensional array and store it in a new variable.
var arr = [[1,0,1,1],[0,1,0,1],[1,0,1,1],[0,1,0,1]];
I know I can traverse the String or even use Regular Expressions to build the array. But I wonder if there is any function similar to eval() in Python to convert the String to an equivalent JS array object directly (despite being a slow process).
var arr = eval("[[1,0,1,1],[0,1,0,1],[1,0,1,1],[0,1,0,1]]");

Considering you have it stored like this
let x = "[[1,0,1,1],[0,1,0,1],[1,0,1,1],[0,1,0,1]]"
let arr = JSON.parse(x)
You array is a valid json that can be parsed and manipulated
let x = "[[1,0,1,1],[0,1,0,1],[1,0,1,1],[0,1,0,1]]"
let arr = JSON.parse(x);
console.log(arr)
Beware that if the string is not a valid json the above code will fail

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

How to stringify an array in Javascript?

I am running the following piece of code:
var arr = [];
arr["aaa"] = {
"xxx" : 1,
"ttt" : 2
};
arr["bbb"] = {
"xxx" : 5,
"qqq" : 6
};
var tmp = JSON.stringify(arr);
alert(tmp);
But the result is []. How does one stringify an array with string keys and object values?
Use
var arr = {};
Arrays should only be used for numerically indexed data, not arbitrary properties. Of course you are able to do it, because they are, in fact, objects. But it won't work in JSON.
Instead, just use objects.
You can't do that, for two reasons:
The stringify method only consider the data in the array, not properties.
There is no JSON format for an array with properties.
If you want the representation of an array in the JSON, you need to put the data in the actual array, not as properties in the array object.
If you want the properties in the JSON, you need to use a plain object instead of an array.

Every character in an array being recognized with ".hasOwnProperty(i)" in javascript as true with Google Apps Script

This is the array:
{"C8_235550":
{"listing":"aut,C8_235550_220144650654"},
"C8_231252":
{"listing":"aut,C8_231252_220144650654"}}
It was fetched with a GET request from a Firebase database using Google Apps Script.
var optList = {"method" : "get"};
var rsltList = UrlFetchApp.fetch("https://dbName.firebaseio.com/KeyName/.json", optList );
var varUrList = rsltList.getContentText();
Notice the .getContentText() method.
I'm assuming that the array is now just a string of characters? I don't know.
When I loop over the returned data, every single character is getting pushed, and the JavaScript code will not find key/value pairs.
This is the FOR LOOP:
dataObj = The Array Shown At Top of Post;
var val = dataObj;
var out = [];
var someObject = val[0];
for (var i in someObject) {
if (someObject.hasOwnProperty(i)) {
out.push(someObject[i]);
};
};
The output from the for loop looks like this:
{,",C,8,_,2,3,5,5,5,0,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,5,5,5,0,_,2,2,0,1,4,4,6,5,0,6,5,4,",},,,",C,8,_,2,3,1,2,5,2,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,1,2,5,2,_,2,2,0,1,4,4,6,5,0,6,5,4,",},}
I'm wondering if the array got converted to a string, and is no longer recognized as an array, but just a string of characters. But I don't know enough about this to know what is going on. How do I get the value out for the key named listing?
Is this now just a string rather than an array? Do I need to convert it back to something else? JSON? I've tried using different JavaScript array methods on the array, and nothing seems to return what it should if the data was an array.
here is a way to get the elements out of your json string
as stated in the other answers, you should make it an obect again and get its keys and values.
function demo(){
var string='{"C8_235550":{"listing":"aut,C8_235550_220144650654"},"C8_231252":{"listing":"aut,C8_231252_220144650654"}}';
var ob = JSON.parse(string);
for(var propertyName in ob) {
Logger.log('first level key = '+propertyName);
Logger.log('fisrt level values = '+JSON.stringify(ob[propertyName]));
for(var subPropertyName in ob[propertyName]){
Logger.log('second level values = '+ob[propertyName][subPropertyName]);
}
}
}
What you have is an object, not an array. What you need to do is, use the
Object.keys()
method and obtain a list of keys which is the field names in that object. Then you could use a simple for loop to iterate over the keys and do whatever you need to do.

How to convert string into an array?

I'm working with this page: ITEM INFO
and I turn the page into a string:
var info = document.getElementsByTagName("pre")[0].innerHTML;
The entire page is already in the format of an array, so is there a conversion function that will convert it from the string into an array?
Use JSON.parse(info) to parse JSON text into Javascript Array.
var info = document.getElementsByTagName("pre")[0].innerHTML;
var results = JSON.parse(info);
Now in results variable will be an array of parsed JavaScript objects.

Trying to convert multi level javascript array to json, with json2 script

I am using the following script to help me convert javascript arrays to json strings: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
How come this works:
var data = [];
data[1] = [];
data[1].push('some info');
data[1].push('some more info');
json_data = JSON.stringify(data);
alert(json_data);
And this does not (returns a blank):
var data = [];
data['abc'] = [];
data['abc'].push('some info');
data['abc'].push('some more info');
json_data = JSON.stringify(data);
alert(json_data);
I want to convert multi-dimensional javascript arrays, but it seems I cannot use stringify() if I name my array keys?
JSON arrays are integer-indexed only.
You can change your first line to use {} as in http://jsfiddle.net/5YXNk/, which is the best you can do here.
Check the array syntax at http://json.org/ -- note arrays contain values only, which will be implicitly indexed by non-negative integers. That's just the way it is.
There is no such thing as an associative array in Javascript. You're going to have to use an object if you want to use string "keys".

Categories

Resources