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.
Related
I have below JSON string
var value = "{'type':'youtube','id':'https://www.youtube.com/embed/JlLGdc71LUc','title':'<strong>mental</strong> <strong>health</strong> & it's benifits for testqaabhi','playerId':'','playerKey':''}";
If I use JSON.parse(value); than it give me error. I just wanted to replace single quote with double quote except that in it's string . Can anybody suggest any method. I had another solution using regular expression to replace it. But I'm calling replace method again and again. So If anybody can minimize it.
value.replace(/^{'/,'{"').replace(/'}$/,'"}').replace(/':'/g,'":"').replace(/','/g,'","')
JSON string is incorrect and coming from other source on which I don't have control. So can't update JSON string.
You can use this.
var xx="{'type':'youtube','id':'https://www.youtube.com/embed/JlLGdc71LUc','title':'<strong>mental</strong> <strong>health</strong> & it's benifits for testqaabhi','playerId':'','playerKey':''}";
JSON.parse(JSON.stringify(xx));
value is an object. (creating from an object literal)
JSON.parse() is used to convert a string containing JSON notation into a Javascript object.
Your code turns the object into a string (by calling .toString()) in order to try to parse it as JSON text.
The default .toString() returns "[object Object]", which is not valid JSON; hence the error.
use JSON.stringify() function for convert your JS object to JSON object... after that you can call JSON.parse() for your JSON object
{
"type": "youtube",
"id": "https://www.youtube.com/embed/JlLGdc71LUc",
"title": "<strong>mental</strong> <strong>health</strong> & its benifits for testqaabhi",
"playerId": "",
"playerKey": ""
}
I would be a valid JSON. Your JSON failed because you have used quote(') on the title.
use this
its benifits for testqaabhi
instead of
it's benifits for testqaabhi
JSON.parse(value.replace(/'/g,"\"").replace(/"s/g,"'"))
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
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
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.
I'm new to javascript so learning how some of this stuff works.
I have a string that looks like: ["{\"name\":\"name\"}","{\"name\":\"Rick\"}"]
If I JSON.parse() that shouldn't it return an array of objects that have a property of name?
What I get is 2 elements in an array but they are just the JSON strings. They are not objects with property name. What am I missing?
[EDIT]
I was calling stringify() on the object and then passing it to the array instead of just passing the object as is to the array. Then I stringify() the array. I was stringifying a stringify which caused it to put the escape characters :)
If I JSON.parse() that shouldn't it return an array of objects that have a property of name?
No, it looks like the JSON defines an array with two strings in it.
This is the JSON for an array with two strings in it:
[
"{\"name\":\"name\"}",
"{\"name\":\"Rick\"}"
]
In JavaScript string literal form, that's '["{\"name\":\"name\"}","{\"name\":\"Rick\"}"]'.
This is the JSON for an array with two objects in it:
[
{
"name": "name"
},
{
"name": "Rick"
}
]
In JavaScript string literal form, that would be '[{"name":"name"},{"name":"Rick"}]'.
I guess its sholuld come as:
"[{\"name\":\"name\"},{\"name\":\"Rick\"}]"
If you lose the (escaped) quotes around the root elements you might get what you want.
E.g. something like
"[{"name":"name"},{"name":"Rick"}]"