JSON.parse Uncaught SyntaxError: Unexpected token o [duplicate] - javascript

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

Related

Transform info in json valid [duplicate]

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.

How to get key values from "array string" in javascript [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Extract values from json string javascript
(3 answers)
Closed 6 years ago.
I have an array in Laravel controller like:
$succeeded[] = array('name' => $name,
'file' => $file
);
...
return $succeeded;
I use an ajax call for getting $succeeded, and I'll have a return string in js function composed of:
"[{"name":"sor.jpg","file":"399393.jpg"}]"
My question is how can I get "name" and "file" values from the string above?
Note: I didn't use any JSON object in controller, but returned just the array. However I wonder it is advantageous to use JSON object.
You first need to parse the response text into a JSON array using the native JSON.parse, and then you can extract the values from the object in the parsed array using dot notation.
var respText = "[{\"name\":\"sor.jpg\",\"file\":\"399393.jpg\"}]";
var arr = JSON.parse(respText)[0]; // Careful - this will throw on invalid JSON
var name = arr.name; // "sor.jpg"
var file = arr.file; // "399393.jpg"

What is a JSON VM747:1 error that happens during JSON parsing? [duplicate]

This question already has answers here:
I keep getting "Uncaught SyntaxError: Unexpected token o"
(9 answers)
Closed 6 years ago.
I'm goofing around with the Star Wars API but don't get why I can't parse the data I get back:
<script>
$.ajax({
url: "http://swapi.co/api/people/1/"
}).done(function( data ) {
console.log(JSON.stringify({'foo': 'bar'})) //returns {"foo":"bar"}
console.log(JSON.parse(JSON.stringify({'foo': 'bar'}))) //returns Object {foo: "bar"}
console.log(data); //returns Object {name: "Luke Skywalker", height: "172", mass: "77", hair_color: "blond", skin_color: "fair"…}
console.log(JSON.parse(data)) // throws error VM747:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
});
</script>
data is already an object as you can see by the fact that the console logs Object { ... }, not something like { ... }.
Straight from the chrome console:
Notice the different output for an object and for a string.
So: You don't have to parse anything, just access data directly.
don't get why I can't parse the data
Passing an object to JSON.parse will convert the object to a string. So you end up doing
JSON.parse('[object Object]')
which throws an error because [object Object] is not valid JSON.

Pase json in javascript [duplicate]

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()

Json object to key value pairs [duplicate]

This question already has answers here:
Fastest way to flatten / un-flatten nested JavaScript objects
(17 answers)
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 8 years ago.
I want to convert
var connection = {
someName:'someValue'
}
to
data:{'connection.someName':'someValue'}
how can i do that?
To elaborate more;
I have
var data ={connection : {name : 'SomeName', url:'SomeUrl'}}
and i post
$.ajax({
type : 'POST'
data : data
....
})
and my back-end expects form data like
connection.name='SomeName'
connection.url='SomeUrl'
so it can bind connection data to Connection bean
Thanks.
Whilst the result you are looking for is technically valid JSON, this will not parse as expected:
var x = JSON.parse("{\"data.someName\":\"someValue\"}");
x.data.someName;
// Error: x.data is undefined
This is because the parser treats the entire literal as a single key, so you would have to access the value like so:
var x = JSON.parse("{\"data.someName\":\"someValue\"}");
x["data.someName"]
// "someValue"
What you actually want in order to be compliant, parsable JSON is this:
{"data":{"someName":"someValue"}}
The parser will treat this appropriately:
var x = JSON.parse("{\"data\":{\"someName\":\"someValue\"}}");
x.data.someName;
// "someValue";

Categories