transform array of strings to array of objects - javascript

I have an array of strings (strings have an object shape). I would like to convert it to an array of objects.
I tried with JSON.parse but am not successful.
let a=["{Axis:1,Value:-74}", "{Axis:2,Value:7}", "{Axis:3,Value:-47}", "{Axis:4,Value:85}"]
Desired result
a=[{Axis:1,Value:-74}, {Axis:2,Value:7}, {Axis:3,Value:-47}, {Axis:4,Value:85}]

You could evaluate the objects, because they are not formatted as JSON standard.
let a = ["{Axis:1,Value:-74}", "{Axis:2,Value:7}", "{Axis:3,Value:-47}", "{Axis:4,Value:85}"],
result = a.map(s => eval(`(${s})`));
console.log(result);

There are a couple of issues here.
The first is that you won't be able to call JSON.parse on a because JSON.parse can only parse strings containing properly formatted JSON.
The second issue is that the strings in your array are not properly formatted JSON.
The solution for this would be to make the strings properly formatted JSON, as follows:
let a=['{"Axis":1,"Value":-74}", '{"Axis":2,Value:7}', '{"Axis":3,"Value":-47}', '{"Axis":4,"Value":85}'];
Then to create an array of those objects, you'll have to use Array.map, as follows:
a = a.map(e => JSON.parse(e));

Related

How to Convert array of Json

var x=[{"name":"james","age":"23"},{"name":"job","age":"55"}];
How to convert array of json object to below response
{{"name":"james","age":"23"},{"name":"job","age":"55"}};
let x=[{"name":"james","age":"23"},{"name":"job","age":"55"}];
console.log(JSON.stringify(x));
The desired output isnt proper JSON. To convert any javascript object into a json string simply use the function JSON.stringify(obj). JSON.parse(string) can be used to create an object out of a string.

How to convert a javascript map of array into a json object in javascript?

I have a javascript MAP object which is holding key as a string and value as a javascript array, each array is holding set of strings inside it. I want to convert the map of arrays into a json object in javascript.
Here is the code which i tried
function addRole() {
var jsonObjectOfMap={};
subMenuSelectedIdMap.forEach(function(items,key,subMenuSelectedIdMap){
jsonObjectOfMap[key]=JSON.stringify(items);
});
alert(JSON.stringify(jsonObjectOfMap));
I am getting the json object as like this
{"1004":"[1005,1006,1023]","1007":"[1008,1053]"}
But is this json format object is valid and what i have to do if i want it the format as this:
{"1004":["1005","1006","1023"]","1007":["1008","1053"]}
Please help me out
If the inner-most values are all numbers and you want them as strings in the end result, you'll have to convert each number individually to a string.
You can do that with another loop over each items using .map() and either calling String() or .toString() for each number:
subMenuSelectedIdMap.forEach(function (items, key, subMenuSelectedIdMap){
jsonObjectOfMap[key] = items.map(function (item) {
return String(item); // or `return item.toString();`
});
});
Optionally, since String() only acknowledges one argument (with the other two that .map() passes being ignored), the loop over items could be shortened to:
jsonObjectOfMap[key] = items.map(String);

How can I properly use the javascript function JSON.parse()?

I have an array that is printed in JSON
[{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Contact":"09197875656","Relation":"Sister"}]
For some reason, I divided the JSON into two parts.
In javascript I used JSON.parse() to decode the JSON above.
for example:
var arr = JSON.parse(response); //The response variable contains the above JSON
alert(arr[0].Name) //Still it outputs John Ranniel, but If i change the content of the alert box on the second part of the JSON,
alert(arr[1].Contact) // It has no output, I don't know if there is a problem with the index of the array.
Make sure your JSON is a string type:
'[{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Emergency Contact":"09197875656","Relation":"Sister"}]'
and then, you can use,
var arr = JSON.parse(response); //The response variable contains the above JSON
console.log(arr[0].Name);
console.log(arr[1]['Emergency Contact']); // There is no 'Contact' property iun your object, and you should use this when there's a space in the name of the property.
See:
var response = '[{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Emergency Contact":"09197875656","Relation":"Sister"}]';
var arr = JSON.parse(response);
console.log(arr[0].Name);
console.log(arr[1]['Emergency Contact']); // There is no 'Contact' property iun your object, and you should use this when there's a space in the name of the property.
You are trying to parse something which is already a JavaScript object, and does not need to be parsed. You need to parse JSON strings. This is not a JSON string. It's a JavaScript object.
Consider the following:
JSON.parse([1,2])
This will coerce the array [1,2] into the string "1,2". JSON.parse will then choke on the ,, since it doesn't belong there in a valid JSON string.
In your case the object will be coerced to the string
"[object Object],[object Object]"
JSON.parse will accept the leading [ as the beginning of the array, then throw on the following character, the o, since it does not belong there in a proper JSON string.
But you say that the JSON.parse worked and resulted in arr. In other words, the parameter you fed to JSON.parse apparently was a string, and was parsed correctly. In that case, the alerts will work fine.
Your JSON structure is array, must be parse to JSON,use JSON.stringify parse this to JSON:
var json = [{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Contact":"09197875656","Relation":"Sister"}];
var str = JSON.stringify(json);
console.log(json);
var arr = JSON.parse(str);
alert(arr[0].Name) //Still it outputs John Ranniel, but If i change the content of the alert box on the second part of the JSON,
alert(arr[1].Contact) // It has no output, I don't know if there is a problem with the index of the array.
Demo: Link
This JSON is array, you can use directly:
var json = [{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Contact":"09197875656","Relation":"Sister"}];
alert(json[0].Name);
alert(json[1].Contact);

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.

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