This question already has answers here:
Safely turning a JSON string into an object
(28 answers)
Closed 7 years ago.
I am trying to parse json in JavaScript
var str = '{"id-1": "www.er.co.uk","id-2": "www.wer.co.uk","id-3": "wer.wer.com","id-4": "www.wwaer.co.uk"}';
var divWebsite = JSON.parse(str);
i am getting error (fiddle)
Uncaught SyntaxError: Unexpected token o
While at the same time my json is valid as you can see here http://jsonlint.com/ (sorry you will need to copy and past json)
That's not JSON. You can see the difference:
http://jsfiddle.net/05dn7mpa/2/
So if you have an string with a json you can parse it. If you've got the propper vanilla object it's parsed !
var divWebsite = JSON.parse('{ "id-1": "www.er.co.uk", "id-2": "www.wer.co.uk", "id-3": "wer.wer.com", "id-4": "www.wwaer.co.uk"}');
In this case you need to pass a string to JSON.parse
HTML
<div id="parsed"></div>
JS
var divWebsite = JSON.parse('{"id-1": "www.er.co.uk","id-2": "www.wer.co.uk","id-3": "wer.wer.com","id-4": "www.wwaer.co.uk"}');
document.getElementById('parsed').innerHTML = divWebsite['id-1'];
JSFIDDLE
What you pass to JSON.parse() is not a string, that's why. You pass an object. In a typical scenario you want JSON.parse to return that object. What you should pass is a string.
If you want to get a json string out of that object use JSON.stringify()
Related
This question already has answers here:
How to convert URL parameters to a JavaScript object? [duplicate]
(34 answers)
Closed 5 months ago.
I am using ajax to send FormData and receiving the output in the following format
Result=A&Status=Approved&Error=&ErrorCode=00000
I want to convert the same into a JS object (key value pair)
e.g.
{Result: "A", Status: "Approved", Error: "", ErrorCode: "00000"}
I can do that using string split and other string functions or regex but since the output format is consistent i was wondering if this is a known data type and if yes is there a way to convert it using native functions?
You can use Object.fromEntries in conjunction with the URLSearchParams constructor.
const obj = Object.fromEntries(new URLSearchParams(
'Result=A&Status=Approved&Error=&ErrorCode=00000'));
console.log(obj);
Take a look at new URLSearchParams(), it should be a way better solution than string manipulation.
This question already has answers here:
Safely turning a JSON string into an object
(28 answers)
Closed 3 years ago.
Transform this result in json valid.
"{\"name\":\"log\",\"hostname\":\"denis-Latitude-E7470\",\"pid\":1007,\"level\":30,\"conextion\":\"DBA MongDB: \[32m%s\[0m\",\"msg\":\"online\",\"time\":\"2019-12-06T13:50:42.510Z\",\"v\":0}"
Just parse it via JSON.parse() to convert the string into a JSON object.
let jsonString = "{\"name\":\"log\",\"hostname\":\"denis-Latitude-E7470\",\"pid\":1007,\"level\":30,\"conextion\":\"DBA MongDB: \[32m%s\[0m\",\"msg\":\"online\",\"time\":\"2019-12-06T13:50:42.510Z\",\"v\":0}";
console.log(JSON.parse(jsonString));
let brokenJsonString = '{ "key": "<div class="coolCSS">some text</div>" }';
try {
console.log(JSON.parse(brokenJsonString));
} catch (e) {
console.log("Exception thrown when parsing.", e.toString());
}
Be careful when parsing strings because (as #Fallenreaper noted) malformed or invalid JSON is going to result in an error thrown. So wrap your JSON.parse() with try...catch statement (more about it here).
Broken/malformed can be handled with libraries like this but use them when you absolutely need it and always read the docs.
This question already has answers here:
Javascript get Object property Name
(4 answers)
Closed 6 years ago.
I have the following JSON data: {"success":"You are welcome"} that I have named json in my JavaScript code.
When I want to alert You are welcome I do json.success. So now the problem I am facing is that, what about if I want to alert success. Is there any way to get it?
So now the problem I am facing is that, what about if I want to alert
success. Is there a need way to get it ?
If your object is
var obj = {"success":"You are welcome"};
You can get the array of keys as
var keys = Object.keys(obj);
and then print it as
console.log( keys[ 0 ] ); //or console.log( keys.join(",") )
var obj = {"success":"You are welcome"};
var keys = Object.keys(obj);
console.log(keys[0]);
You mean something like this?
keys = Object.keys(json_object)
key_to_use = keys[0];
Try this code
alert(Object.keys({"success":"You are welcome"})[0]);
Since you're able to do json.success, you don't have "JSON data", you have a Javascript Object. JSON, or JavaScript Object Notation, is no more than the serialization of a Javascript object.
As other answers have stated, you can use Object.keys() to list the fields of an object.
Object.keys() can be called on any JavaScript object to get back a list of keys.
This question already has answers here:
How to parse JSON easily?
(3 answers)
Closed 6 years ago.
The String I am talking about was initially a part of a JS object like:
var nameVal = "Jacob";
var favNumbersVal = "{\"firstNum\":0, \"secondNum\":1, \"thirdNum\":2}";
var aJSObject = {
"name" = nameVal,
"favNumbers" = favNumbersVal
};
The variable I am interested in is favNumbersVal. Please notice that the starting and ending " around the value of favNumbersVal are the normal double quotes we put around a String whenever we define a String.
The format of the value of favNumbersVal is coming from a library dynamically.
The question is that how do I convert the value of favNumbersVal to a JS object, so that when I later convert sJSObject to JSON using JSON.stringify(), the value of aJSObject becomes a JSON object, and the value of favNumbers becomes a JSON object nested inside the aforementioned JSON object.
Using JSON.parse():
var favNumbersVal = "{\"firstNum\":0, \"secondNum\":1, \"thirdNum\":2}";
console.log(JSON.parse(favNumbersVal));
This question already has answers here:
Error "Uncaught SyntaxError: Unexpected token with JSON.parse"
(24 answers)
Closed 7 years ago.
I have this JSON :
var data = [{
"ID":1,"Name":"Test",
"subitem": [
{"idenID":1,"Code":"254630"},
{"idenID":2,"Code":"4566"},
{"idenID":3,"Code":"4566"}
]
}];
console.log(JSON.parse(data)); //Uncaught SyntaxError: Unexpected token o
How to de-serialize data to javascript object.
It already is an object ... of type Array. To access the Object:
var foo = data[0];
alert(foo.ID);
JSON.parse takes a String and parses it into an equivalent JavaScript value.
This is usable in Javascript. You need to parse JSON when your data is in String format and you get it from server side.
The purpose of JSON.parse is to convert to Javascipt Object Notation to use it. For example,
var str = "{"a":1,"b":2}";
var obj = JSON.parse(str); //obj = {a:1, b:2}
Reference MDN