I must be missing something here, but the following code (Fiddle) returns an empty string:
var test = new Array();
test['a'] = 'test';
test['b'] = 'test b';
var json = JSON.stringify(test);
alert(json);
What is the correct way of JSON'ing this array?
JavaScript arrays are designed to hold data with numeric indexes. You can add named properties to them because an array is a type of object (and this can be useful when you want to store metadata about an array which holds normal, ordered, numerically indexed data), but that isn't what they are designed for.
The JSON array data type cannot have named keys on an array.
When you pass a JavaScript array to JSON.stringify the named properties will be ignored.
If you want named properties, use an Object, not an Array.
const test = {}; // Object
test.a = 'test';
test.b = []; // Array
test.b.push('item');
test.b.push('item2');
test.b.push('item3');
test.b.item4 = "A value"; // Ignored by JSON.stringify
const json = JSON.stringify(test);
console.log(json);
Nice explanation and example above. I found this (JSON.stringify() array bizarreness with Prototype.js) to complete the answer. Some sites implements its own toJSON with JSONFilters, so delete it.
if(window.Prototype) {
delete Object.prototype.toJSON;
delete Array.prototype.toJSON;
delete Hash.prototype.toJSON;
delete String.prototype.toJSON;
}
it works fine and the output of the test:
console.log(json);
Result:
"{"a":"test","b":["item","item2","item3"]}"
I posted a fix for this here
You can use this function to modify JSON.stringify to encode arrays, just post it near the beginning of your script (check the link above for more detail):
// Upgrade for JSON.stringify, updated to allow arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
Another approach is the JSON.stringify() replacer function param. You can pass a 2nd arg to JSON.stringify() that has special handling for empty arrays as shown below.
const arr = new Array();
arr.answer = 42;
// {"hello":"world","arr":{"answer":42}}
JSON.stringify({ hello: 'world', arr }, function replacer(key, value) {
if (Array.isArray(value) && value.length === 0) {
return { ...value }; // Converts empty array with string properties into a POJO
}
return value;
});
Alternatively you can use like this
var test = new Array();
test[0]={};
test[0]['a'] = 'test';
test[1]={};
test[1]['b'] = 'test b';
var json = JSON.stringify(test);
alert(json);
Like this you JSON-ing a array.
Json has to have key-value pairs. Tho you can still have an array as the value part. Thus add a "key" of your chousing:
var json = JSON.stringify({whatver: test});
Related
I want to convert a JSON string into a set of array containing the values from the JSON. after json.stringify(jsonmybe) and alert it display [{"role":"noi_user"},{"role":"bert_user"}] (which i saw as a JSON). I want to get the noi_user and bert_user and set them into a javascript array. something like ['noi_user','bert_user'] with quotes in each value.
I did the var stringy = json.parse() and the alert showing [object Object]. and further add this lines
for (var i = 0; i < stringy.length; i++) {
arr.push(stringy[i]['role']);}
and the arr I get was a value with comma when in alert but the comma missing as i display them in the text field and it becomes a long string like noi_userbert_user
What I really want is from [{"role":"noi_user"},{"role":"bert_user"}] to ['noi_user','bert_user']
Use JSON.parse and then reduce to get what you want,
var s = `[{"role":"noi_user"},{"role":"bert_user"}]`
var arr = []
try {
arr = JSON.parse(s).reduce((acc, val)=>[...acc, val.role], [])
} catch (e){
console.log("Invalid json")
}
console.log(arr)
Is this what you are loking for ? You can map on your array and just extract the role attribute of each datum.
const jsonString = ...
const data = JSON.parse(jsonString).map(data => data.role);
console.log(JSON.stringify(data, null, 2));
JSON uses double quotes to delimit strings and field names.
So you have a JSON string like
'[{"role":"noi_user"},{"role":"bert_user"}]'
You want to convert it to an object, then extract values of "role" fields of each element, put them all into an array.
Your example json string contains an array of user objects within "role" fields. Following code takes this list, loops through each user object and puts role's of each object into a separate array roleList.
var jsonStr = '[{"role":"noi_user"},{"role":"bert_user"}]';
var userObjList = JSON.parse(jsonStr);
var roleList = [];
userObjList.forEach(userObj => {
roleList.push(userObj.role);
});
console.log(roleList);
You could make a custom function to produce a sort of array_values in PHP but an indented and 2D level like so:
function array_values_indented (input) {
var tmpArr = []
for (key in input) {
tmpArr.push(input[key]['role']);
}
return tmpArr
}
var object = JSON.parse('[{"role":"noi_user"},{"role":"bert_user"}]');
var result = array_values_indented(object);
console.log(result);
I have an object that looks like this
{'{"variable":"2","text":"fdsfdsfds","hotdog":"yes"}': '' }
I want to access part of what's contained in it
For example, if it was a normal object I would've thought I could do
objectName.variable
or
objectName.["variable"]
First of all, You should parse json data.
var obj = JSON.parse('{"variable":"2","text":"fdsfdsfds","hotdog":"yes"}');
console.log(obj.variable);
console.log(obj.text);
etc ...
Firstly, parse the JSON - then because the data is a key, use Object.keys, then get the variable property:
const obj = {'{"variable":"2","text":"fdsfdsfds","hotdog":"yes"}': '' };
const { variable } = JSON.parse(Object.keys(obj)[0]);
console.log(variable);
var obj = {'{"variable":"2","text":"fdsfdsfds","hotdog":"yes"}': '' };
// get keys from obj
var keys = Obejct.keys(obj);
// loop keys array
keys.forEach((item) => {
// !!! parse String to JSON !!!
var parsedObj = JSON.parse(item);
console.log(parsedObj.variable);
})
How can I convert a JavaScript associative array into JSON?
I have tried the following:
var AssocArray = new Array();
AssocArray["a"] = "The letter A"
console.log("a = " + AssocArray["a"]);
// result: "a = The letter A"
JSON.stringify(AssocArray);
// result: "[]"
Arrays should only have entries with numerical keys (arrays are also objects but you really should not mix these).
If you convert an array to JSON, the process will only take numerical properties into account. Other properties are simply ignored and that's why you get an empty array as result. Maybe this more obvious if you look at the length of the array:
> AssocArray.length
0
What is often referred to as "associative array" is actually just an object in JS:
var AssocArray = {}; // <- initialize an object, not an array
AssocArray["a"] = "The letter A"
console.log("a = " + AssocArray["a"]); // "a = The letter A"
JSON.stringify(AssocArray); // "{"a":"The letter A"}"
Properties of objects can be accessed via array notation or dot notation (if the key is not a reserved keyword). Thus AssocArray.a is the same as AssocArray['a'].
There are no associative arrays in JavaScript. However, there are objects with named properties, so just don't initialise your "array" with new Array, then it becomes a generic object.
Agreed that it is probably best practice to keep Objects as objects and Arrays as arrays. However, if you have an Object with named properties that you are treating as an array, here is how it can be done:
let tempArr = [];
Object.keys(objectArr).forEach( (element) => {
tempArr.push(objectArr[element]);
});
let json = JSON.stringify(tempArr);
I posted a fix for this here
You can use this function to modify JSON.stringify to encode arrays, just post it near the beginning of your script (check the link above for more detail):
// Upgrade for JSON.stringify, updated to allow arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
You might want to push the object into the array
enter code here
var AssocArray = new Array();
AssocArray.push( "The letter A");
console.log("a = " + AssocArray[0]);
// result: "a = The letter A"
console.log( AssocArray[0]);
JSON.stringify(AssocArray);
If I create a JavaScript object like:
var lst = [];
var row = [];
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
And then convert it to a string:
JSON.stringify(lst);
The result is an object containing an empty object:
[[]]
I would expect it to serialize like:
[[Col1 : 'val1', Col2: 'val2']]
Why do the inner objects properties not serialize?
Code snippet at JSFiddle.
Because row is an array, not an object. Change it to:
var row = {};
This creates an object literal. Your code will then result in an array of objects (containing a single object):
[{"Col1":"val1","Col2":"val2"}]
Update
To see what really happens, you can look at json2.js on GitHub. This is a (heavily reduced) snippet from the str function (called by JSON.stringify):
if (Object.prototype.toString.apply(value) === '[object Array]') {
//...
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
//...
}
//...
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
//...
}
//...
}
//...
Notice that arrays are iterated over with a normal for loop, which only enumerates the array elements. Objects are iterated with a for...in loop, with a hasOwnProperty test to make sure the proeprty actually belongs to this object.
You use your inner array like an object, so make it an object instead of an array.
var lst = [];
var row = {};
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
or use it as an array
var lst = [];
var row = {};
row.push( 'val1' );
row.push( 'val2' );
lst.push(row);
You want row to be a dictionary, not a vector. Define it like this:
var row = {};
Since an array is a datatype in JSON, actual instances of Array are stringified differently than other object types.
If a JavaScript Array instance got stringified with its non-numeric keys intact, it couldn't be represented by the [ ... ] JSON array syntax.
For instance, [ "Col1": "val1"] would be invalid, because JSON arrays can't have explicit keys.
{"Col1": "val1"} would be valid - but it's not an array.
And you certainly can't mix'n'match and get { "Col1": "val1", 1, 2, 3 ] or something.
By the way, this works fine:
var lst = [];
var row = {};
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
alert(JSON.stringify(lst));
How can I convert a JavaScript associative array into JSON?
I have tried the following:
var AssocArray = new Array();
AssocArray["a"] = "The letter A"
console.log("a = " + AssocArray["a"]);
// result: "a = The letter A"
JSON.stringify(AssocArray);
// result: "[]"
Arrays should only have entries with numerical keys (arrays are also objects but you really should not mix these).
If you convert an array to JSON, the process will only take numerical properties into account. Other properties are simply ignored and that's why you get an empty array as result. Maybe this more obvious if you look at the length of the array:
> AssocArray.length
0
What is often referred to as "associative array" is actually just an object in JS:
var AssocArray = {}; // <- initialize an object, not an array
AssocArray["a"] = "The letter A"
console.log("a = " + AssocArray["a"]); // "a = The letter A"
JSON.stringify(AssocArray); // "{"a":"The letter A"}"
Properties of objects can be accessed via array notation or dot notation (if the key is not a reserved keyword). Thus AssocArray.a is the same as AssocArray['a'].
There are no associative arrays in JavaScript. However, there are objects with named properties, so just don't initialise your "array" with new Array, then it becomes a generic object.
Agreed that it is probably best practice to keep Objects as objects and Arrays as arrays. However, if you have an Object with named properties that you are treating as an array, here is how it can be done:
let tempArr = [];
Object.keys(objectArr).forEach( (element) => {
tempArr.push(objectArr[element]);
});
let json = JSON.stringify(tempArr);
I posted a fix for this here
You can use this function to modify JSON.stringify to encode arrays, just post it near the beginning of your script (check the link above for more detail):
// Upgrade for JSON.stringify, updated to allow arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
You might want to push the object into the array
enter code here
var AssocArray = new Array();
AssocArray.push( "The letter A");
console.log("a = " + AssocArray[0]);
// result: "a = The letter A"
console.log( AssocArray[0]);
JSON.stringify(AssocArray);