Why I can't parse JSON in JavaScript? - javascript

JSON contains one object:
results[0] = { 'MAX(id)': 1 }
And this code doesn't work:
var text = results[0];
var obj = JSON.parse(text);
console.log(obj.MAX(id));

results[0] is already an object type
You can parse only from string to object like this:
JSON.parse('{ "MAX(id)": 1 }');

Your object is already a JSON. You don't need to parse it.
To access MAX(id) property, you can use [] notation as follows:
results[0] = { 'MAX(id)': 1 };
console.log(results[0]['MAX(id)']);

Your result[0] is a real javascript object. JSON.parse transforms text into objects, so you can't parse other objects with it.

var results = { 'MAX(id)': 1 };
//var text = results;
//var obj = JSON.parse(text);
alert(results['MAX(id)']);

Related

JSON.stringify not printing all fields [duplicate]

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

Converting JSON value into JavaScript array

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

How to access part of string contained in an object in Javascript

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

Javascript Inserting an object "inside"(each index having object already) an array of objects

I hava a json response like [{0},{1},{2}..] and each index contains object data. I also have an object like a{} which also contains object data.What I want is to add the object a "inside"(at the end) the each index like [{0..a},{1..a},{2a}].
Parse the json response using JSON.parse then iterate over it and add the object inside each object
var resp = '[{"data":"1"},{"data":"2"},{"data":"3"},{"data":"4"}]';
var arr = JSON.parse(resp);
console.log(arr);
var a = {
data: 5
};
arr.forEach(function(element,i) {
arr[i].a = a;
});
console.log(arr)
So assuming your json response is in some variable (let's say its called jsonResponse) and a is an Object you can do:
jsonResponse.push(a)
Which will add the a object to the end of the jsonResponse array.
This assumes that jsonResponse is an array, if it is a string you may have to do something like:
let jsonResponse = JSON.parse(responsestring)
Your question is not totally clear, but sounds like you want to look at array.map.
For example:
let arr = [{x:1,y:2},{x:3,y:4}];
const foo = arr.map(obj=>{obj.z=42; return obj})
console.log("GOT:", foo);
to combine two json objects:
function combineObj(ob1, ob2) {
return Object.fromEntries(Object.entries(ob1).concat(Object.entries(ob2)));
}
var a = [{b:1},{q:3},{s:2}],
b = {a:2};
var result = a.map(x=>combineObj(x,b));
console.log(result);
From what I understand you want to add Object A to every Object in your JSON response?
If so try:
var jsonResponse = [{a: 1}, {a: 1}, {a: 1}]
var objToAppend = {b:2}
for(var objectInJsonResponse of jsonResponse){
objectInJsonResponse.appendedObject = objToAppend;
}
This will result in:
console.log(jsonResponse)
[{a:1,appendedObject:{b:2}},{a:1,appendedObject:{b:2}},{a:1,appendedObject:{b:2}}]
Of course you can change the name of appendedObject to whatever you want the key to be.

How can I turn a json object into a javascript array

So, I need to convert a json object like this {"0":"sometext","1":"someothertext"} into a javascript array with the index matching the integer and the data at the index the string. I tried using JSON.parse() but it didn't work since this happens.
var json = '{"0":"sometext","1":"someothertext"}';
var obj = JSON.parse(json);
//Then when I would want to assign a part of the object to a variable this gives me an error
var somevar = obj.0;
You can simply iterate over every property in the object and assign them as values in the array:
var obj = {"0":"sometext","1":"someothertext"};
var arr = [];
Object.keys(obj).forEach(function (key) {
arr[key] = obj[key]
});
Use bracket notation:
Change
var somevar = obj.0;
to
var somevar = obj[0];

Categories