Validated JSON throwing SyntaxError: Property must be a string literal - javascript

I have a validated JSON that I'm pulling into my app, but as soon as I choose an item related to the JSON the app just goes into a forever "loading" cycle.
The error I receive is Error: Uncaught (in promise): SyntaxError: JSON Parse error: Property name must be a string literal.
Here is my validated JSON:
{
"lodges": [
{
"title": "Lakeside Lodge",
"url_title": "lakeside-lodge",
"lodges_short_name": "Lakeside",
"lodges_description": "<h5><strong>Coming Soon: Estimated Opening Fall 2021 </strong></h5><p>The Lakeside Lodge sits will rest in the center of this premier state park, Lakeside State Park.</p>",
"lodges_summary": "<p>Anticipated opening in Fall 2021, the new 85-room Lodge at Lakeside State Park!</p>",
"reservation_link": "null"
}
]
}
Here is the code I am using to get and display in the data:
showAmenities(item){
let list : any;
let res : any;
switch (item) {
case 'lodges':
this.data.getParkLodges(this.park).then(data => {
let res = JSON.parse(data);
let list = res.lodges;
this.openAmenityListPage(item,list);
}
}
}
openAmenityListPage(item,list){
let amenitiesModal = this.modalCtrl.create(ParkAmenitiesListPage, {title : item, listItems: list, park: this.parkDetails.title, parkShortName: this.parkShortName });
amenitiesModal.present();
}
I am able to get data and display other JSON's that are identical, but for some reason this one is throwing this error.
Edit: I am working with other APIs with HTML tags within their values, and those are working perfectly fine.

Your JSON string contains escaped double quotes: <a href=\"/parks/lakeside\">.
The escaping "gets lost" as soon as the JSON code is interpreted as a string by Javascript. Escaped quotes in a string become normal quotes:
console.log('a text with \"quotes\".') // --> logs 'a text with "quotes"'.
So in your case, the actual string that JSON.parse() sees, and that leads to a parse error, is like:
'{ "lodges_description": "<a href="/parks/lakeside">" }, ...'
You need to escape the escape character, so that Javascript knows you want to pass the actual backslash character to the JSON.parse() function:
console.log('a text with \\"quotes\\".') // --> logs 'a text with \"quotes\"'.

Turns out there was a relationship API with a channel I was working with that contained an extra comma. :D
This question is closed.

Related

even the json is correct json parse not working in java script?

var data={
"apple_scab": {
"sym": "Dark velvet covering on leaves, Velvety olive-green to black spots on leaves",
"cause": "Venturia inaequalis",
"nc_c": "Use resistant varieties: Prima, Priscilla, Sir Prize, Jonafree, Red free, Dayton, Pristine, Goldrush, Enterprise or Liberty.",
"c_c": "Use fungicide such as Captan."
}}
The above JSON is parsed successfully by most of the online parsers
also, I can directly put this in js console in browser and I am able to read from the console.
If I assign to a variable when using json.parse() with variable giving an error:
var obj = JSON.parse(data);
*VM568:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at <anonymous>:1:6*
JSON.parse accepts a string, which is parsed and then returns an object full of the parsed data. But you are passing it an object. data is already parsed, so you don't need JSON.parse here at all.
You are getting this error Unexpected token o in JSON at position 1 because of some weird quirks of javascript. Basically, it's trying to coerce the object into a string so that it can be parsed. And objects get coerced to string as simply [object Object]. So you are actually running
JSON.parse('[object Object]')
This is invalid json, and the error tells you the first character of the string that is invalid.
But in your case, you can simply use data without parsing.
var data={
"apple_scab": {
"sym": "Dark velvet covering on leaves, Velvety olive-green to black spots on leaves",
"cause": "Venturia inaequalis",
"nc_c": "Use resistant varieties: Prima, Priscilla, Sir Prize, Jonafree, Red free, Dayton, Pristine, Goldrush, Enterprise or Liberty.",
"c_c": "Use fungicide such as Captan."
}
}
console.log(data.apple_scab.cause) //-> Venturia inaequalis
So from what I gather, you are trying to parse an object that is already an object.
let someObject = { hello: "world" };
JSON.parse(someObject);
This will fail because JSON.parse() can not parse an object.
In order for that to succeed, it must a string.
let someJsonString = '{ "hello": "world" }';
let myObject = JSON.parse(someJsonString);
console.log(myObject);
This will succeed and parse the object.

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 .

Trying to parse json source with javascript [duplicate]

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

How to handle failed JQuery DOM conversion

I have a common function to display errors as a result of an AJAX call. Some of those messages are HTML strings, which I want to convert to a DOM object then search for elements inside it using .find(). Others will be just strings (not HTML). In this case, I don't know how to handle this...it is generating exceptions.
var messageTest = "" + this;
if ($(messageTest).length == 0) {
message += this;
} else {
message += $(messageTest).find('.message-error').html();
}
FYI, "this" in this case seems to be a String object with an array in which each item is a character, so in the inspector, it isn't showing "my message here" but:
[0]: "m"
[1]: "y"
etc
When it is just a string, which is not HTML, I get an error at the if statement line:
Uncaught Error: Syntax error, unrecognized expression:<The contents of messageText>
So how to I gracefully handle this when the input could be an HTML string or just a string?
Note...in the end, I just want the string, as I am going to wrap it in it's own HTML.
If it's either a string or HTML, it can always be appended to an element, and then sorted out:
var msg = $('<div />').append(this),
err = msg.find('.message-error'),
txt = err.length ? err.text() : msg.text();
message += txt;
append the string or HTML to an empty div, if the div contains a .message-error element, get the text of that element, otherwise get the text of the div, which would equal the original string etc.
One way, very close to what you have, is to catch the exception, and in this case consider it's a string (assuming this contains the response string):
var messageString = this;
var messageDOM;
try {
messageDOM = $(messageString);
} catch(ex) {
// If we got here, messageString is not HTML
messageDOM = $('<div/>').text(messageString);
}
I know this doesn't answer your question, but I feel like what you're wanting can be better accomplished by a slight change in methodology.
If you have control of the server sending these responses, i would recommend sending them back as JSON objects, if you make every result a JSON object then you can set an error property to true/false in the object that comes back along with a message value with your HTML or error message.
This is faster on the client system as well since its a native object to javascript and jquery has excellent JSON support using $.getJSON.

Regex to wrap JSON property value inside another string. MongoDB transition

I'm trying to insert some data from a proprietary JSON database into MongoDB for testing purposes. My data is currently in a json file in the format:
{ "_id": "213124123114",
"foo":bar",
"otherId": "2324242424",
...
}
To keep my test data relationships intact, I want to use sed to wrap all the _id and xxxId values with ObjectId(...)
My data would then look like:
{ "_id": ObjectId("213124123114"),
"foo":bar",
"otherId": ObjectId("2324242424"),
...
}
I would then take the data and insert it into mongo in the same format as displayed in the file.
I'm testing my regex in javascript, but the following assignment blows up:
var y = s/"_id":(\s?"[0-9]+"),/ObjectId($1)/gi
SyntaxError: Unexpected token :
Escaping the ':' doesn't seem to do anything.
When I remove the capture flag at the start, the regex assignment works as expected
var y = /"_id":(\s?"[0-9]+"),/
var p = "\"_id\": \"123123123121321212312\",";
y.test(p) === true
but I have no way to capture the value block I need to wrap.
Any ideas what I'm doing wrong?
Try this:
json.replace(/("(?:_id|otherId)": ?)("\d+")/g, '$1ObjectId($2)');
Here's a fiddle: http://jsfiddle.net/7WJBm/1/

Categories