How does JSON get converted from a string to an object? - javascript

Behind the scenes, is JSON created using eval?
If not, how does the string '{"val1":1,"val2":2}' get turned into an object where .val1 == 1 and .val2 == 2?

JSON is usually converted into a JavaScript object using a JSON parser. Browsers nowadays come with one which can be accessed via the parse method of the JSON object. The traditional pollyfill is json2.js.
That string, however, is not JSON and cannot be parsed with a JSON parser.

try this
var obj = JSON.parse(string);
or this is another way
JSONObject jsonObj = new JSONObject("{\"val1\":\"1\",\"val2\":\"2\"}");

Related

Convert JSON Serialized String Containing HTML Entities into object

I have a string that looks like this:
"["Software","3rd Party"]"
How can I convert this to an object in javascript?
I familiar with converting HTML Entities to DOM Objects:
$("<div/>").html(encodedStr).text();
My situation is a little different than the one above. I don't want to create HTML, I need to create an object.
Use the built-in JSON.parse:
var jstr = $("<div/>").html(encodedStr).text();
var obj = JSON.parse(jstr);
Since you're using jQuery anyway, you can use $.parseJSON() instead of JSON.parse() if you need to support browsers older than IE8. (jQuery simply calls JSON.parse() when it's available.)
You can use "he" library with JSON.parse. "he" can encode and decode HTML code.
var str = he.decode("["Software","3rd Party"]");
var obj = JSON.parse(str);

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

JavaScript - Converting JSON object to String

I have a JSON object in following format which I need to convert to pure String...as 0000-0000-0000-0000-000 so I was wondering how I can do this in Javascript?
{ KEY: "0000-0000-0000-0000-000" }
try this (where data is the data returned from the API call)
var tokenString = data.KEY;
alert(tokenString);
try
console.log(obj)
to view it in the browser debugger console
or
JSON.stringify(obj);
I would recommend using
JSON.stringify()
Extra info on this method can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Your object is not JSON when it's in JavaScript, it's JavaScript code. The string version you're asking for is JSON (JavaScript Object Notation). This is why you can do things in JavaScript that you cannot do in JSON, like representing functions and binary data.
The function you're looking for to turn your JavaScript object into JSON is JSON.stringify() which you would use like this:
var obj = { }; //put your object here
console.log(JSON.stringify(obj)); //output the JSON version of your object
Also, the object in your question is not valid JSON or JS. In either scenario you'd need to put quotes around the 0000-0000-0000-0000-0000 and give it a value. The following is valid JSON:
{ "0000-0000-0000-0000-0000": null }
Store your response in one variable and then do
response.KEY

Query regarding Difference between JavaScript Object And JSOn Object

Here is my question:
in java script:
we hav an object:
var someObject={"name":"somename"};
Now we want to get the name ,we ll do
alert(someObject.name); //it will print somename Right?
Same object i get from a source which sends a JSON object as
someJSONObject={"name":"someName"};
Now in my javascript code ,without parsing this someJSONObject ,i can get name as
alert(someJSONObject.name);
If it is so ,why we need to convert JSON Object to a javaScript Object by parsing it ,when we can use it as an object without parsing or using eval()?
Thanks !
Because it's not a JSON Object. The syntax {"name":"someName"}, with quoted keys, does not make it JSON, the same syntax is supported by Javascript object literals.
JSON can be embedded in Javascript strings. Like:
var json = '{"key": "value"}';
Then you can parse it into Javascript data types:
var obj = JSON.parse( json );
Note that eval may cause syntax errors because the syntaxes of JSON and Javascript are not ultimately compatible. The above would have caused a syntax error if evaled.
JSON is a string, so it's something like var jsonObject = '{"name":"someName"}'; an object is an object.

How to parse/use this JSON in Javascript

I have a variable with the following in my code:
{
"Rows":
[
{
"New":1,
"CachedNumberType":0,
"Date":1327479615921,
"Type":2,
"Number":"123456",
"Duration":1
}
]
}
I think it's JSON, how do I parse it? (E.g., with json2.js?) Or how do I use it in my JavaScript?
var jsonObj = JSON.parse(jsonString);
You've said that when you try JSON.parse on the variable containing the "JSON" that it says it can't parse it. Could it be that it's already deserialized? Or maybe it was never JSON at all? For instance, what you quoted, in JavaScript source, is an object literal containing an array literal containing another object literal; no JSON in sight.
If you do console.log(x.Rows[0].Date);, where x is the variable you were trying to pass to JSON.parse, do you see the date value?
A lot of people confuse JSON and JavaScript literal syntax, because JSON is a textual format derived from JavaScript literal syntax. I suspect that's what's happening here.

Categories