my array has keys with double-quotes "" around them, how can I remove them?
I'm generating my object from input fields like this:
var obj = {};
obj.Firstname = document.getElementById("firstName").value;
obj.Lastname = document.getElementById("surname").value;
var jsonStringObj = {
users: [JSON.stringify(obj)]
};
console.log(jsonStringObj)
Result is like this:
users: ["{"Firstname":"","Lastname":""}"] <<-- wrong
Expected array:
users: [{Firstname:"john",Lastname:"doe"}] <<-- I want this
I have tried the following unsuccessful attempts:
var string = JSON.stringify(array);
string.replace (/"/g,'');
When you write JSON.stringify to convert it in the string, it would add the double quotes to your keys.
You just have to write obj directly, it would behave as the normal object and not string.
So please update your code of lines with the below code. It should resolve your problem.
var obj = {};
obj.Firstname = document.getElementById("firstName").value;
obj.Lastname = document.getElementById("surname").value;
var jsonStringObj = {users: [obj]};
console.log(jsonStringObj)
You can use JSON.parse(),this will change a json to object. here is the example:
var obj = JSON.parse(users)
if you want to change an object to string you use JSON.stringify(obj)
There is no need to stringify the object at all.
var obj = {};
obj.Firstname = "";
obj.Lastname = "";
var obj2 = {users: [obj]};
console.log(obj2);
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 want to push my object without a key in my javascript array. Right now the issue is I psuh my object in the array, but I add extra key 0,1,2 ... I don't want that key. Is there any solution for that? Here I add the code that I implemented.
let newArr = [];
let myId = data['id'];
var key = myId;
var obj = {};
myobj[key] = {
data: "testdata"
};
newArr.push(myobj);
The above code generates output like below. I don't want that 0 key in my array
0: {
260: {
data: 'testdata'
},
}
It's hard to tell what you're wanting, but I expect you don't want to be using an array here at all? You just want a single object that contains all of your key-value pairs?
e.g. something like this:
const data = { id: 1234 };
let myId = data['id'];
var key = myId;
var myobj = {};
myobj[key] = {
data: "testdata"
};
console.log(myobj);
// You can then add more data
myobj[2345] = {
data: "more test data"
};
console.log(myobj);
// Example Property Access
console.log(myobj[2345])
Try this
newArr.push(...myobj);
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);
})
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];
I have created a JSON object and put it under session object.
How can I retrieve the value from the JSON?
This is my program
var datainsession = {"firstName":"John", "lastName":"Doe"};
var keyname = 'test';
window.sessionStorage.setItem(keyname + '', datainsession);
var val_sess = window.sessionStorage.getItem(keyname);
var firstname = val_sess.firstName;
alert(firstname);
http://jsfiddle.net/5bea0mr2/3/
Could you please tell me how I can retrieve the first name?
Session storage can only hold strings, not objects. Your session here ends up holding your object converted to a string ("[Object object]"), and not the object itself.
To get around this we can firstly convert the object to a JSON string using JSON.stringify():
window.sessionStorage.setItem(keyname + '', JSON.stringify(datainsession));
-> '{"firstName":"John","lastName":"Doe"}'
Then when pulling it convert it back to an object by using JSON.parse():
var val_sess = JSON.parse(window.sessionStorage.getItem(keyname));
-> {"firstName":"John","lastName":"Doe"}
window.sessionStorage.setItem can only store serialised objects.
So you have to serialise it first via JSON.stringify:
window.sessionStorage.setItem(keyname, JSON.stringify(datainsession))
Then to retrieve it via JSON.parse:
var val_sess = window.sessionStorage.getItem(keyname);
var obj = JSON.parse(val_sess);
// obj.firstName is what you need.
JSON is represented by a string, not an object. It's simply a JavaScript object with string keys. You'll need to use JSON.stringify() and JSON.parse() to convert the JavaScript object.
Try the following:
var datainsession = {
firstName: "John",
lastName: "Doe"
};
var keyname = 'test';
window.sessionStorage.setItem(keyname, JSON.stringify(datainsession));
var val_sess = JSON.parse(window.sessionStorage.getItem(keyname));
var firstname = val_sess.firstName;
alert(firstname);
You need to convert it to a string on setting, and parse it when you get it out. This method only stores a string, but JSON methods can get around that. Eg.
var datainsession = {"firstName":"John", "lastName":"Doe"};
var keyname = 'test';
window.sessionStorage.setItem(keyname + '', JSON.stringify(datainsession));
var val_sess = window.sessionStorage.getItem('test');
var obj = JSON.parse(val_sess).firstName;
alert(obj);