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,"'"))
Related
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 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.
I want to understand the basic differences clearly between Javascript object and JSON string.
Let's say I create the following JS variable:
var testObject = {one: 1,"two":2,"three":3};
Q1. Is the key/property name valid both with/without quotes? (e.g. "one" : 1)
If yes, what is the difference?
Q2: If I convert the above object using JSON.stringify(testObject), what’s the difference between the original JS object and the JSON?
I feel they are almost the same. Please elaborate on this.
Q3: For parsing a JSON string, is the method below recommended?
var javascriptObj = JSON.parse(jSonString);
Is the key/property name valid both with/without quotes ?
The only time you need to enclose a key in quotes when using Object Literal notation is where the key is a reserved word or contains a special character (if, :, - etc). It is worth noting that a key in JSON must be enclosed in double quotes.
If I convert the above object to JSON using var jSonString = JSON.stringify(testObject);, what is the difference between the 2 (JS obj and JSON)?
JSON is a data interchange format. It's a standard which describes how ordered lists and unordered maps, strings, booleans and numbers can be represented in a string. Just like XML and YAML is a way to pass structured information between languages, JSON is the same. A JavaScript object on the other hand is a physical type. Just like a PHP array, a C++ class/ struct, a JavaScript object is a type internal to JavaScript.
Here's a story. Let's imagine you've purchased some furniture from a store, and you want it delivered. However the only one left in stock is the display model, but you agree to buy it.
In the shop, the chest-of-drawers you've purchased is a living object:
var chestOfDrawers = {
color: "red",
numberOfDrawers: 4
}
However, you can't send a chest-of-drawers in the post, so you dismantle it (read, stringify it). It's now useless in terms of furniture. It is now JSON. Its in flat pack form.
{"color":"red","numberOfDrawers":4}
When you receive it, you then rebuild the chest-of-drawers (read, parse it). Its now back in object form.
The reason behind JSON, XML and YAML is to enable data to be transferred between programming languages in a format both participating languages can understand; you can't give PHP or C++ your JavaScript object directly; because each language represents an object differently under-the-hood. However, because we've stringified the object into JSON notation; i.e. a standardised way to represent data, we can transmit the JSON representation of the object to another language (C++, PHP), they can recreate the JavaScript object we had into their own object based on the JSON representation of the object.
It is important to note that JSON cannot represent functions or dates. If you attempt to stringify an object with a function member, the function will be omitted from the JSON representation. A date will be converted to a string;
JSON.stringify({
foo: new Date(),
blah: function () {
alert('hello');
}
}); // returns the string "{"foo":"2011-11-28T10:21:33.939Z"}"
For parsing a JSON string, is the method below recommended? var javascriptObj = JSON.parse(jSonString);
Yes, but older browsers don't support JSON natively (IE <8). To support these, you should include json2.js.
If you're using jQuery, you can call jQuery.parseJSON(), which will use JSON.parse() under the hood if it's supported and will otherwise fallback to a custom implementation to parse the input.
Q1: When defining object literals in javascript, the keys may include quotes or not. There is no difference except that quotes allow you to specify certain keys that would cause the interpreter to fail to parse if you tried them bare. For example, if you wanted a key that was just an exclamation point, you would need quotes:
a = { "!": 1234 } // Valid
a = { !: 1234 } // Syntax error
In most cases though, you can omit the quotes around keys on object literals.
Q2: JSON is literally a string representation. It is just a string. So, consider this:
var testObject = { hello: "world" }
var jSonString = JSON.stringify(testObject);
Since testObject is a real object, you can call properties on it and do anything else you can do with objects:
testObject.hello => "world"
On the other hand, jsonString is just a string:
jsonString.hello => undefined
Note one other difference: In JSON, all keys must be quoted. That contrasts with object literals, where the quotes can usually be omitted as per my explanation in Q1.
Q3. You can parse a JSON string by using JSON.parse, and this is generally the best way to do it (if the browser or a framework provides it). You can also just use eval since JSON is valid javascript code, but the former method is recommended for a number of reasons (eval has a lot of nasty problems associated with it).
Problems solved by JSON
Let's say you want to exchange regular JavaScript objects between two computers, and you set two rules:
The transmitted data must be a regular string.
Only attributes can be exchanged, methods are not transmitted.
Now you create two objects on the first host:
var obj1 = { one: 1,"two":2,"three":3 }; // your example
var obj2 = { one: obj1.one, two: 2, three: obj1.one + obj1.two };
How can you convert those objects into strings for transmission to the second host?
For the first object, you could send this string obtained form the literal definition '{ one: 1,"two":2,"three":3 }', but actually you can't read the literal in the script portion of the document (at least not easily). So obj1 and obj2 must actually be processed the same way.
You need to enumerate all attributes and their value, and build a string similar to the object literal.
JSON has been created as a solution to the needs just discussed: It is a set of rules to create a string equivalent to an object by listing all attributes and values (methods are ignored).
JSON normalizes the use of double-quotes for attribute names and values.
Remember that JSON is a set of rules only (a standard).
How many JSON objects are created?
Only one, it is automatically created by the JS engine.
Modern JavaScript engines found in browsers have a native object, also named JSON. This JSON object is able to:
Decode a string built using JSON standard, using JSON.parse(string). The result is a regular JS object with attributes and values found in the JSON string.
Encode attributes / values of a regular JS object using JSON.stringify(). The result is a string compliant with the JSON set of rules.
The (single) JSON object is similar to a codec, it's function is to encode and decode.
Note that:
JSON.parse() doesn't create a JSON object, it creates a regular JS object, there is no difference between an object created using an object literal and an object created by JSON.parse() from a JSON-compliant string.
There is only one JSON object, which is used for all conversions.
Going back to the questions:
Q1: The use of single of double quotes is allowed for object literals. Note that the quotes are used optionally for attributes names, and are mandatory for string values. The object literal itself is not surrounded by quotes.
Q2: Objects created from literals and using JSON.parse() are strictly the same. These two objects are equivalent after creation:
var obj1 = { one: 1, "two": 2, "three": 3 };
var obj2 = JSON.parse('{ "one": "1", "two": "2", "three": "3" }');
Q3: On modern browsers JSON.parse() is used to create a JS object from a JSON-compliant string. (jQuery has also an equivalent method that can be used for all browsers).
Q1 - in JS you only need to use quotes if the key is a reserved word or if it would otherwise be an illegal token. In JSON you MUST always use double quotes on key names.
Q2 - the jsonString is a serialised version of the input object ...
Q3 - which may be deserialised to an identical looking object using JSON.parse()
Question already has good answers posted, I am adding a small example below, which will make it more easy to understand the explanations given in previous answers.
Copy paste below snippet to your IDE for better understanding and comment the
line containing invalid_javascript_object_no_quotes object declaration to avoid compile time error.
// Valid JSON strings(Observe quotes)
valid_json = '{"key":"value"}'
valid_json_2 = '{"key 1":"value 1"}' // Observe the space(special character) in key - still valid
//Valid Javascript object
valid_javascript_object_no_quotes = {
key: "value" //No special character in key, hence it is valid without quotes for key
}
//Valid Javascript object
valid_javascript_object_quotes = {
key:"value", //No special character in key, hence it is valid without quotes for key
"key 1": "value 1" // Space (special character) present in key, therefore key must be contained in double quotes - Valid
}
console.log(typeof valid_json) // string
console.log(typeof valid_javascript_object_no_quotes) // object
console.log(typeof valid_javascript_object_quotes) // object
//Invalid Javascript object
invalid_javascript_object_no_quotes = {
key 1: "value"//Space (special character) present in key, since key is not enclosed with double quotes "Invalid Javascript Object"
}