Add quotation marks to JSON Object attributes - javascript

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

Related

how can I remove the quote or pass this string as normal array

events: "[{id:"3",title:"activity",start:"2017-03-11 00:00:00",allDay:true},{id:"4",title:"nutrition",start:"2017-03-11 00:00:00",allDay:true}]"
how can I remove the quote or pass this string as normal array in angularjs2?
It's a JSON string. just use JSON.parse and you'll get array of objects.
Here, the string in events object is not a valid JSON. So u can't use JSON.Parse here. For valid JSON key should be wrapped in double quote eg: {id:...} should be {"id":...}
let input = {
events: '[{id:"3",title:"activity",start:"2017-03-11 00:00:00",allDay:true},{id:"4",title:"nutrition",start:"2017-03-11 00:00:00",allDay:true}]'
};
let dataToSend = Object.assign({}, input);
dataToSend.events = eval(dataToSend.events);
console.log(dataToSend);
Since, your input sting is still a valid javascript object you can use eval method for conversion. Here I used object.assign to create a copy of your input. So, any modification to dataToSend will not affect your actual input object.
let input = {
events: '[{id:"3",title:"activity",start:"2017-03-11 00:00:00",allDay:true},{id:"4",title:"nutrition",start:"2017-03-11 00:00:00",allDay:true}]'
};
eval(obj.events);

JSON.stringify converts object's property names into strings

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.

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...

Access JSON object to get Resource Bundle key/value pair

I know how to access key value pair from JSON object but in my case, the resource bundle keys are mapped to values.
e.g.
var json = {"label.name.first":"foo","label.name.second":"bar"};
Here json.label.name.first doesn't give me "foo".
Can someone help me with this?
Due to using the period character (.) in the key name, you need to use the [] notation to access its value.
console.log( json['label.name.first'] );
Additionally, you have a JavaScript object, not JSON.
The difference between a JavaScript object or JSON is that JSON is always a string. Secondly, JavaScript objects don't require the same quote standards on the key names.
If you just consider the string below, then yes it can be considred JSON (this is why if you paste it into a JSON parser, it tells you it's valid JSON):
{"label.name.first":"foo","label.name.second":"bar"}
However, if you assign that directly to a JavaScript variable then you have a JavaScript object literal, not JSON. This is because JSON is also a valid JavaScript object/array literal when it is not contained in a string:
var obj = {"label.name.first":"foo","label.name.second":"bar"};
If you were to use it as a string, then it is JSON:
var json = '{"label.name.first":"foo","label.name.second":"bar"}';
// json is a string, so it's JSON
var obj = JSON.parse(json); // parse the JSON into an object
The confusion is quote common because the JSON format is very similar to the format of JavaScript object and array literals.
Do this:
json["label.name.first"]
However, I think you are misunderstanding the . notation.
And BTW your json isn't a JSON, it is a javascript object and not its notation.
It's json["label.name.first"] that would get you "foo". Since your property's name contains characters that cannot be used in variable names.
If you're expecting to access these properties using the syntax json.label.name.first then your JSON needs to be:
var json = {
"label":{
"name":{
"first":"foo",
"second":"bar"
}
}
}
This is not right way to create object, you should create one like this.
var json={"label":{"name":{"first":"foo","second":"bar"}}};
it will also work as json string

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