Trying to parse json source with javascript [duplicate] - javascript

This question already has answers here:
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 8 years ago.
I am trying to parse json source with javascript.
I have this json source:
var exam = '{
status : 'connected',
authResponse: {
accessToken: 'it is accessToken',
expiresIn:'2014-06-19',
signedRequest:'it is signedRequest',
userID:'mp172'
}
}';
To parse, I use JSON.parse(exam);
After this source, it is not working. I want to parse this source with javascript.

Actually, your json source is not valid.
According to JSON.org, member should be quote by "
Change exam to {"status":"connected","authResponse":{"accessToken":"it is accessToken","expiresIn":"2014-06-19","signedRequest":"it is signedRequest","userID":"mp172"}}

Take a look at JSON.stringify and JSON.parse.
var exam = {status : 'connected', authResponse: { accessToken: 'it is accessToken', expiresIn:'2014-06-19', signedRequest:'it is signedRequest', userID:'mp172' }};
// stringify the response first
stringify = JSON.stringify(exam);
// stringified result
console.log(stringify);
// parse the json
final = JSON.parse(stringify);
// parsed final result
console.log(final);
Here is the jsfiddle example

Your JSON is invalid , it should look something like this ,
{
"status": "connected",
"authResponse": {
"accessToken": "itisaccessToken",
"expiresIn": "2014-06-19",
"signedRequest": "itissignedRequest",
"userID": "mp172"
}
}
JSONLint show following error ,

"Proper" json data has both the property name and string values in double quotes. Browser parsers are very lenient though and the reason I think yours is failing is because it isn't a valid string. When you open the string with ', the string ends on the next ' it finds, so it should be choking when it tries to make sense of connected', after finding the string '{ status : '. If you wrapped your JSON in single double quotes (since it uses single quotes for values) that would probably work, but comphilip is right.

If you intended it to be a string to start with, make sure it is in one line. Otherwise, use (+) to append the string and then use JSON.parse to parse it to an object.
var exam = '{"status" : "connected","authResponse": {"accessToken": "it is accessToken","expiresIn":"2014-06-19","signedRequest":"it is signedRequest","userID":"mp172"}}'
var obj = JSON.parse(exam);

Related

Converting string to object with Javascript (Error: Unexpected token t in JSON at position 1)

I'm using Editor.js which outputs data as JSON and save that as String in DynamoDB. When I query that data, I want to convert that back to an Object.
Converting the string with JSON.parse() gives me Error: Unexpected token t in JSON at position 1 message.
var json = '{time=1558311121067, blocks=[{type=paragraph, data={text=writing something first}}], version=2.13.0}';
obj = JSON.parse(json);
Not sure what this error message means.
I will suggest to correct the JSON from the origin itself if you can,
if you can't than you need to replace = with : and than stringify and parse
({[^=]+|,[^=]+)=
| |_________ Replaces `=` which is preceded by `,`
|_________________ Replaces `=` which is preceded by `{`
let json = '{time=1558311121067, blocks=[{type=paragraph, data={text=writing something first}}], version=2.13.0}';
json = json.replace(/({[^=]+|,[^=]+)=/g,"$1"+':')
let obj = JSON.parse(JSON.stringify(json));
console.log(obj)
On side note:- This is code is considering above given example data, it can be updated based on the kind of values your JSON can have

json - can't access json parameter

Here is my code
var data = '{"coord":{"lon":74.34,"lat":31.55},"weather":[{"id":711,"main":"Smoke","description":"smoke","icon":"50d"},{"id":701,"main":"Mist","description":"mist","icon":"50d"}],"base":"cmc stations","main":{"temp":304.6,"pressure":1002,"humidity":62,"temp_min":304.15,"temp_max":305.15},"wind":{"speed":5.1,"deg":130},"clouds":{"all":20},"dt":1466901000,"sys":{"type":1,"id":7133,"message":0.0035,"country":"PK","sunrise":1466899176,"sunset":1466950287},"id":1172451,"name":"Lahore","cod":200}'
setWeather(data);
function setWeather(data) {
var json = JSON.parse(JSON.stringify(data));
alert(json['main']['temp']);
$('#temp').html(json['main']['temp']);
}
And I can't seem to figure out why I'm not able to access the json object parameter. Anyone know what the issue is?
Thanks in advance.
Let us to some basic debugging:
> var data = '{"coord": ... }';
> typeof data
"string"
So far so good, data is a string.
> JSON.stringify(data);
""{\"coord\": ... }""
> typeof JSON.stringify(data);
"string"
Apparently JSON.stringify(data) also returns a string. We can see the same value contained in data but now including surrounding quotes (note the double "" at the beginning and the end) and escaped quotes (\").
So what exactly does JSON.stringify do? It will convert any JavaScript value to JSON. Some examples:
> JSON.stringify([]) // array
"[]"
> JSON.stringify(true) // array
"true"
> JSON.stringify("foo") // string
""foo""
We can see that passing a string simply produces another JSON encoded string, so that doesn't seem particular helpful. But you are also using JSON.parse, so lets see what effect that has:
> JSON.parse(JSON.stringify(data))
"{"coord": ... }"
> typeof JSON.parse(JSON.stringify(data))
"string"
It seems using JSON.parse returns a string again. This shouldn't be too surprising since we are passing a string value to JSON.stringify, which will encode it as a JSON string. Parsing this result must give us back the original value, which was a string. We can verify that easily:
> JSON.parse(JSON.stringify(data)) === data
true
Yep.
So that doesn't help us converting data to a JavaScript object. Lets just try JSON.parse instead:
> JSON.parse(data)
Object {coord: Object, weather: Array[2], base: "cmc stations", main: Object, wind: Object…}
That looks much better. Since data contains a JSON encoded object, JSON.parse converts that value to a JavaScript object.
I your example, data is a string, not a javascript object, so you don't need to use JSON.stringify, remove it and it should work:
var data = '{"coord":{"lon":74.34,"lat":31.55},"weather":[{"id":711,"main":"Smoke","description":"smoke","icon":"50d"},{"id":701,"main":"Mist","description":"mist","icon":"50d"}],"base":"cmc stations","main":{"temp":304.6,"pressure":1002,"humidity":62,"temp_min":304.15,"temp_max":305.15},"wind":{"speed":5.1,"deg":130},"clouds":{"all":20},"dt":1466901000,"sys":{"type":1,"id":7133,"message":0.0035,"country":"PK","sunrise":1466899176,"sunset":1466950287},"id":1172451,"name":"Lahore","cod":200}'
setWeather(data);
function setWeather(data) {
//NOTE: only parse is needed
var json = JSON.parse(data);
alert(json['main']['temp']);
$('#temp').html(json['main']['temp']);
}
data is a String because of the single quotes , so if you called JSON.stringify(data) will add another double quotes to data , which means in order to convert data to JS object you will need to call JSON.parse(data) two times .
var obj ='{hello:1}'; //string
var json= JSON.stringify(obj);
console.log(json); // "\"{hello:1}\""
console.log(JSON.parse(json)); //"{hello:1}" => still a string
To get your code running correctly by converting data to object , just remove the JSON.stringify()
function setWeather(data) {
var json = JSON.parse(data); // remove JSON.stringify() => now json is object
alert(json['main']['temp']);
$('#temp').html(json['main']['temp']);
}

Javascript JSON parse and stringify for multi levels

I have a javascript object that contains a property with values of another json stringified object. I cannot get the printout version of the string back to object form. See the following code. the console.log output content of json string is exactly as right side of jsonFromStr. However, JSON.parse(json) is OK, while JSON.parse(jsonFromStr) is error. What is wrong here?
jsfiddle: http://jsfiddle.net/jma7889/qtmmpj2t/
level2Obj = { key2a: "foo", key2b: 3};
level2ObjJson = JSON.stringify(level2Obj);
level1Obj = {key1a: "bar", key1b: {level2ObjJson}};
json = JSON.stringify(level1Obj);
jsonFromStr = '{"key1a":"bar","key1b":{"level2ObjJson":"{\"key2a\":\"foo\",\"key2b\":3}"}}'; // same than json
objFromStrify = JSON.parse(json); // OK
objFromAssignedString = JSON.parse(jsonFromStr); // Uncaught SyntaxError: Unexpected token l in JSON at position 45
If you do this it will work:
jsonFromStr = '{"key1a":"bar","key1b":{"level2ObjJson":"{\\\"key2a\\\":\\\"foo\\\",\\\"key2b\\\":3}"}}';
The reason that your version does not work is that the escape sequence \" is resolved at that very moment, and so the actual value of jsonFromStr will be:
'{"key1a":"bar","key1b":{"level2ObjJson":"{"key2a":"foo","key2b":3}"}}'
... which is invalid JSON.
You need to keep those escapes unresolved in the JSON string, and this you do by escaping the escape sequence itself with additional slashes.
jsonFromStr = '{"key1a":"bar","key1b":{"level2ObjJson":{\"key2a\":\"foo\",\"key2b\":3}}}';
You have an extra "" for value of level2ObjJson key,replace jsonFromStr in your code with the above code .

JSON String inside a JSON

I want to create a JSON string inside a JSON request. Here is my code,
Fiddle
JS
var x = {
a: 1,
b: 'a sample text',
};
var request = {
t: JSON.stringify(x),
c: 2,
r: 'some text'
};
console.log(request);
Can someone help me how to escape the double quotes?
Console
Object {
t: "{"a":1,"b":"a sample text"}", //This creates a problem, double quotes inside double quotes.
c: 2,
r: "some text"
}
Thanks in advance.
There is no problem. It's just your console.log that shows all strings by simply delimiting with ".
As you say this request object is used in a JSON request, where it will be JSON.stringifyed another time, with the valid result
{"t":"{\"a\":1,\"b\":\"a sample text\"}","c":2,"r":"some text"}
That's just the way the browser console shows you the value of a string, by wrapping in double quotes for the output. This is perfectly normal and nothing is broken.
You can test it by transforming your JSON string back to an object and using a property.
console.log( JSON.parse(request.t).b ); // a sample text
Well, this may not be helpful. But, I ran into an issue where the JSON string inside a JSON had no property. I was able to parse the JSON string doing the following:
//Return from remote php request {'{"firsttest": 0, ""scndTest": 1"}'};
// How to access
let data = Object.Keys(jsonWJsonString)[0];
let justJSONValue = JSON.parse(data);
this works because there is no object property to reference so an index value can be used; which gives us the JSONString. Hope that helped anyone. Cheers

convert "converted" object string to JSON or Object

i've following problem and since i upgraded my prototypeJS framework.
the JSON parse is not able anymore to convert this string to an object.
"{empty: false, ip: true}"
previously in version 1.6 it was possible and now it needs to be a "validated" JSON string like
'{"empty": false, "ip": true}'
But how can i convert the 1st example back to an object?
JSON needs all keys to be quoted, so this:
"{empty: false, ip: true}"
is not a valid JSON. You need to preprocess it in order to be able to parse this JSON.
function preprocessJSON(str) {
return str.replace(/("(\\.|[^"])*"|'(\\.|[^'])*')|(\w+)\s*:/g,
function(all, string, strDouble, strSingle, jsonLabel) {
if (jsonLabel) {
return '"' + jsonLabel + '": ';
}
return all;
});
}
(Try on JSFiddle) It uses a simple regular expression to replace a word, followed by colon, with that word quoted inside double quotes. The regular expression will not quote the label inside other strings.
Then you can safely
data = JSON.parse(preprocessJSON(json));
It makes sense that the json parser didn't accept the first input as it is invalid json. What you are using in the first example is javascript object notation. It's possible to convert this to an object using the eval() function.
var str = "({empty: false, ip: true})";
var obj = eval(str);
You should of course only do this if you have the guarantees the code you'll be executing is save.
You can find more information about the json spec here. A json validator can be found here.
edit: Thai's answer above is probably a better solution
const dataWithQuotes = str.replace(/("(\\.|[^"])*"|'(\\.|[^'])*')|(\w+)\s*:/g, (all, string, strDouble, strSingle, jsonLabel) => {
if (jsonLabel) {
return `"${jsonLabel}": `;
}
return all;
});
return dataWithQuotes
similar solution as above , but updated with arrow functions.

Categories