JSON.stringify converts object's property names into strings - javascript

I have an object like this.
var obj = {
name: "foo",
age: 23
};
for (i in obj) {
if (obj[i] == "foo") {
obj[i] = "bob";
}
}
After manipulating the object
when using JSON.stringify(obj) i getting the output like this.
{"name":"bob","age":23}
But i don't need the objects property as string how to convert into objects property name. so i need the ouput like this {name:"bob",age:23}. Please correct me if i am wrong.

This looks like the right output.
In the wiki the example looks the same WIKI JSON
In JS that shouldnt be a problem at all.
Pls look at this to parse your JSON string back to an object JSON.parse
Maybe it would be smarter to tell us why you need to remove the double qoutes from the key. Probably JSON is not the problem, I would look at the implementation.

You don't need to do this, as {"name":"bob","age":23} is valid JSON. But if you really want to remove the quotes around the keys:
var json = JSON.stringify(obj);
var keyVals = json.substr(1,json.length-2).split(/,/g);
var output = "{";
keyVals.forEach(function(keyVal) {
var parts = keyVal.split(":");
output += parts[0].replace(/"/g, "");
output += ":";
output += parts[1];
output += ",";
});
output = output.substr(0, output.length - 1);
output += "}";

As Anirudha said. if you want to remove the double quote of keys, you need regular expression. As fllows:
JSON.stringify(obj).replace(/"([^"]*)":/g, '$1:')

Yes we can use the regular expression to solve this problem
console.log(JSON.stringify({"name":"bob","age":23}).replace(/\"([^(\")"]+)\":/g,"$1:"))

Parsing an object with JSON.stringify(obj) does not read just your properties values, but also your properties names in order to transform an object into a JSON string ( example syntax style look in package.json where bouth properties and values have parenthases ). Your object properties become strings because the object is stringified, so if you dont want properties to be strings don use JSON.stringify() on the object.

Related

Parse result of API response that looks like JSON array (of type string) back into array?

How can we convert an array of type string back into array.
var arr = '[ "abc", "def"]';
console.log(typeof arr) ==> String
How can i convert it back into an array?
I am getting this array in form of string from an API response. and these are errors which can be multiple. I want to convert them into an array such that i can display them on their correct positions.
If your string is really as shown in your edit (not your original question), it's valid JSON, so you could use JSON.parse:
var str = '["abc", "def"]';
var arr = JSON.parse(str);
Since your array syntax conforms to that of a JSON array: Use a JSON parser.
Browsers have one built-in these days.
arr = JSON.parse(arr);
For a more general approach, you would need to look at eval, but that has numerous drawbacks (including issues of scope, speed, and security).
You can't convert it back, since you don't actually have an array.
an array should be created without the single quotes ... you are creating a string, you want to do something like the following if you want to create an array.
var arr = ["string 1","string 2"];
UPDATE
Since you updated your question, with information regarding why you had a string, you can follow the suggested solution:
JSON.parse(arr);
Use JSON.parse() to convert the JSON string into JSON object.
DEMO
var arr = '[ "abc", "def"]';
console.log(typeof arr); // string
var arr = JSON.parse('[ "abc", "def"]');
console.log(typeof arr); // object

Get value from json "undefined" what I have wrong?

I have this string:
[
{"id":"001",
"name":"Charlie"},
{"id":"002",
"name":"Ellie"},
]
Them, I save this string in a variable and I parse it:
function parseJSON(string){
var mylovelyJSON = JSON.stringify(string);
alert(mylovelyJSON[id]);
}
When I make my alert, I get and "undefined", I also tried with "mylovelyJSON.id", And I get the same.
Could not be a Json? I get this string from an php array.
There are many things wrong here
Your JSON is invalid
You have an extra , just before the end of the array that you need to remove
You need to parse
JSON.stringify converts a JavaScript data structure into a string of JSON.
You need to go the other way and use JSON.parse.
Square-bracket notation takes strings
mylovelyJSON[id] takes the value of id (which is undeclared so, in this case, would throw a reference error) and gets the property with the name that is the same as that value.
You need either mylovelyJSON["id"] or mylovelyJSON.id
You have an array
Your JSON consists of an array of objects, not a single object.
You need to get an object out of the array before you can access properties on it.
mylovelyJSON[0]["id"]
var json_text = '[{"id":"001","name":"Charlie"},{"id":"002","name":"Ellie"}]';
parseJSON(json_text);
function parseJSON(string){
var result_of_parsing_json = JSON.parse(string);
document.body.appendChild(
document.createTextNode(result_of_parsing_json[0]["id"])
);
}
Two things are wrong here
Your array ends with a comma, which isn't valid json
You are converting a string to javascript, and stringify does the opposite of that.
So something like this might work:
var id = 0;
function parseJSON(string){
var mylovelyJSON = JSON.parse(string);
alert(mylovelyJSON[id]);
}
Note I am assuming that id is a global variable...

Add quotation marks to JSON Object attributes

How do I add quotation marks to a JSON Object attributes for example like this:
{name:"User 01"}
so it should look like that afterward:
{"name":"User 01"}
both of them are strings
JSON.stringify(eval('{name:"User 01"}'));
Not really great but works.
Assuming the first example is a Javascript object, you could convert it into a JSON string using JSON.stringify:
JSON.stringify({name:"User 01"});
outputs: "{"name":"User 01"}"
Assuming String
If the first example is a string, I think you would have to parse through it with methods like split.
the first notation
var string = {name:"user 01"}
if you use it then you can directly access all the properties and methods of the string object
but if you use this notation :
var string = {"name":"user 01"}
then you have to use :
window.JSON.parse("'"+string+"'")
Update:
Now that we have ES6, you can use template literals :
window.JSON.parse(`'${string}'`)
in order to access all the methods and properties of string object
the last notation is used generally when getting data back from php script
or something like that
Use this:
function JSONify(obj){
var o = {};
for(var i in obj){
o['"'+i+'"'] = obj[i]; // make the quotes
}
return o;
}
console.log(JSONify({name:'User 01'}));

Javascript accessing the string variable as array

I just tried this code in Chrome deveoper tools:
var str = "1111111";
str[0] = 2;
2
console.log(str[0]);
1
As you can see, the output was 1, where I expected 2. My conclusion is this is not meant to be working like that, so I ask how would I get this to work - how would I change the first 'item' of the varable str to 2?
That is because in JavaScript strings are immutable objects. You should use substr function:
String.prototype.replaceAt = function (index, char) {
return this.substr(0, index) + char + this.substr(index + char.length);
};
var str = '11111';
console.log(str.replaceAt(0, '2'));
From the rhino book:
In JavaScript, strings are immutable objects, which means that the characters within them may not be changed and that any operations on strings actually create new strings. Strings are assigned by reference, not by value. In general, when an object is assigned by reference, a change made to the object through one reference will be visible through all other references to the object. Because strings cannot be changed, however, you can have multiple references to a string object and not worry that the string value will change without your knowing it.
Try this out
str.replace(str.charAt(0), "2")
You need to split the string first.
So something like:
str = str.split('');
Then you can treat it as an array.

Creating json keys on the fly

I would like to create a json object to send as a post array, but I need to create the key on the fly
var id = $('#myInput').val();
var post = {
'product[123]': 'myValue', // this works fine - but isn't dynamic
'product['+id+']': 'myValue' // this does not work
}
Sending it in as a string works fine, but I get an issue when I want to make it more dynamic. Am I missing something really simple here, or am I trying to do something Javascript isn't supposed to do?
(Note that this has nothing to do with JSON. You're not using JSON there, you're using an object initializer. JSON is a textual (not code) format, which is a subset of JavaScript's object initializer syntax.)
Do it outside the object initializer, using [] notation:
var id = $('#myInput').val();
var post = {};
post[product[id]] = 'myValue';
That will take the value (at runtime) of product[id] and use that as the key for the property. If you wanted the key to literally be product[123] when id is 123, you'd use this instead:
post['product[' + id + ']'] = 'myValue';
A more generic discussion:
var a = "foo";
var obj = {};
obj[a] = "bar";
console.log(obj.foo); // "bar"
JavaScript allows you to specify property keys in two ways: Using dotted notation and a literal (obj.foo), or using bracketed notation and a string (obj["foo"]). In the latter case, the string doesn't have to be a string literal, it can be the result of any expression.
Try
post['product[' + id + ']'] = 'myValue';
Why do you use '[ ]' in ids of the object? Avoid to do this.
In your sample, you can do this by the following code:
var id = $('#myInput').val();
var post = {
'123': 'myValue',
id: 'myValue'
}
Or, if you realy realy want to use an arrry (actually, all objects ARE array in JavaScript).
You can write this:
var product=[];
product['123']='something';
product[id]='another';

Categories