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];
Related
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});
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);
})
I am storing a Hashmap in JSP in a hiddeninput element
How can I parse it into a JSON object in my javascript??
When i print the hidden input variable value in my JS output is something like this:
{zipcode=560036, fmid=xyz, quantity=1}
It is better to pass a JSON string from server so you can easily parse. If you have a simple object structure like this (your example) you can try split it and take eack key/value pair. here is a example
var mapAsStr = "{zipcode=560036, fmid=xyz, quantity=1}";
var convertToObj = function(str) {
var obj = {};
str.replace(/\{|\}/g, '').split(',').forEach(function(pair) {
var keyVal = pair.split("=");
var key = keyVal[0].trim();
var val = keyVal[1].trim();
val = isNaN(val) ? val : parseFloat(val);
obj[key] = val;
});
return obj;
}
console.log(convertToObj(mapAsStr));
But note you can proceed with this only if you have a flat object structure with primitive values.
I have an object of values and I am trying to populate two arrays with the keys and values from the object.
My Object:
obj = {19455746: 7476, 22489710: 473}
Loop attempting to append data:
var sensorNameArray = [];
var sensorDataArray = [];
for(var i in obj) {
sensorNameArray.push[i];
sensorDataArray.push[obj[i]];
}
At the moment the two arrays are printing out as empty. My expected outout would be something like:
sensorNameArray = [19455746, 22489710];
sensorDataArray = [7476, 473];
push is a function, not an array, it uses parenthesis not brackets :
for(var i in obj) {
sensorNameArray.push(i);
sensorDataArray.push(obj[i]);
}
The syntax push[] doesn't invoke the function, it tries to access a property of the function object. It doesn't throw an error because in Javascript, functions ARE objects and this syntax is technically valid.
So, just fix the syntax to push() in order to actually invoke the function.
You are using square braces []
but array.push() is a function so use circle braces instead
Try the following code
obj = {19455746: 7476, 22489710: 473};
var sensorNameArray = [];
var sensorDataArray = [];
for(var i in obj) {
sensorNameArray.push(i);
sensorDataArray.push(obj[i]);
}
This is working and tested.
A different syntax (more elegant IMO) :
var sensorNameArray = Object.keys(obj)
var sensorDataArray = Object.values(obj)
or :
var sensorDataArray = sensorNameArray.map( key => obj[key] )
Best way to deal with JSON is use lodash or underscore.
_.key() and _.value are functions for your requirement.
Eg.:
obj = {19455746: 7476, 22489710: 473};
sensorNameArray = _.keys(obj);
sensorDataArray = _.values(obj);
If you want to proceed in your way, then you can use parenthesis as push inbuilt function of Javascript for inserting element into array.
Correct is:
for(var i in obj) {
sensorNameArray.push(i);
sensorDataArray.push(obj[i]);
}
I am using an array as defined below
cat_id = Object { 2="text", 3="TKL1", -1="Select an Attribute"}.
when i am trying to retrieve the length of "cat_id" as
var l = cat_id.length;
its showing the length as "undefined".
But, I am unable to get the length of "cat_id". I am unable to use replace(), indexOf() and split() functions.
for example:
var index = cat_attr.indexOf(",")
Its showing error as below:
TypeError: cat_attr.indexOf is not a function
This isn't array, this is Object. Array defined in this way: [1,2,3]. If you want retrieve the "length" of object you can do this in this way:
var students = {job:92, adam:67,sara:83};
var studentNames = Object.keys(students);
var studentsLength = studentNames.length;
If you want split object to array you can do this in this way:
var students = {jon:92, adam:67,sara:83};
var studentNames = Object.keys(students);
var studentArray = studentNames.map(function(name){
var student = {};
student.name = name;
student.grade = students[name];
return (student);
}); // [{name:jon,grade:92},{name:adam,grade:67},{name:sara,grade:83}]
cat_id variable you defined as not an array, it is a javascript object. That is why it is not behaving like array! [] is the array notation. Use array notation [] instead of {} object notation you have used.
Your problem is wrong type and wrong syntax.
In your question your cat_id is an Object, not string or array. So you can not call length() or indexOf() funtion.
Moreover, you typed wrong syntax, it should be:
var cat_id = { 2: 'text', 3: 'TKL1', -1: 'Select an Attribute'}.
Here is how to retrieve property count (size and/or length)
size_obj = Object.keys(my_object).length;
As in
size_cat_id = Object.keys(cat_id).length;