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

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".

Related

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

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

Remove multiple square brackets using replace() - javascript

I have a response from the server that is like this:
users: ["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]
It's a string not an array like it appear, since I need an array to work on, how I can remove the square backets and then the commas to obtain a normal array?
I've tried in this way:
var data = ["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]
data.replace('[', '').replace(']', '').split(',');
but chaining two .replace() functions and a split() isn't the best solution. Can anyone halp me?
In your example data is an array.
However, if data was a string you would convert it to an array like this:
var arr = JSON.parse(data);
In short,
Here you have provided data in normal string formate not in JSON string formate
var data = 'users: ["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]'
var squareBracketData = data.substr(data.indexOf("["))
var array = JSON.parse(squareBracketData)
console.log(array)
Some personal advice, Try to send JSON stringify data from the
server so it will make your life easy
Example:
var users =["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]
// Stringify data
var data = JSON.stringify({users})
console.log("Data")
console.log(data)
// retrieve data from string
var parsedData = JSON.parse(data)
var parsedUsers = parsedData.users
console.log("parsedUsers")
console.log(parsedUsers)

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.

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