read a json string which has a "'" (malformed?) - javascript

I need to consume a service which is returning JSON. I have no influence whatsoever on that service (third party).
If I do
JSON.parse (data)
I get an
SyntaxError: Unexpected token
I know the service works because the error occurs depending on input parameters.
In other words, sometimes it definitely works! The HTTP response code is 200 so it is not some kind of access error, and it is repeatable.
Can I assume they are returning malformed JSON?
Writing the data as a text file to disk and reading it like this:
fs = require('fs')
fs.readFile 'output.json', '', (err, data) ->
if err?
console.log err
json = JSON.parse(data)
console.log json
returns
undefined:1
De L\'Embustier
^
SyntaxError: Unexpected token '
at Object.parse (native)
which is kind of strange because it seems as if the string is correctly escaped but it's nevertheless not being read correctly.
The file is 300+k; haven't seen how to attach it.
EDIT:
Response from jsonlint.com
Parse error on line 1297:
... "Address": "36 Rue De L\'Embust
-----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
EDIT2:
Here is the whole file then:
http://pastebin.com/ACUfvPCx

The service is indeed returning malformed JSON.
There is no \' escape sequence in JSON. It's perfectly valid to escape any character in Javascript, but JSON uses a subset of the Javascript syntax and only allows escaping characters that actually could need escaping. As an apostrophe is not used as a string delimiter in JSON, it never needs escaping.
If you can't get the service fixed, you would need to request the JSON as plain text, replace the escaped apostrophes with just the apostrophe itself, then parse the text as JSON.

Related

why JSON.parse does not convert a string to json object?

I tried to convert a string to a javascript object using JSON.parse but it's not working.
I tried everything but did not get anything on the console.log and there is no error message.
JSON.parse(`{'exp': '1', 'input': '1d6404f66ed3d72e', 'iterate': 'no'}`);
Update
In the real code, I'm passing the value from an object
console.log(JSON.parse(future.onIOPub.data['text/plain']))
When you run this, you should see
Uncaught SyntaxError: Unexpected token ' in JSON at position 1
This error is because you are using single quotes. JSON only accepts double quotes, as described in the spec
https://www.json.org/json-en.html

Error parsing JSON data - "Uncaught SyntaxError: Unexpected token ."

I'm getting the error below in Chrome while parsing a JSON data. The data sample is at http://jsoneditoronline.org/?id=31ffc7c0e7e1a9a2adf641306497b57a This is a valid JSON and my server is sending the correct Content-Type value (application/json).
Uncaught SyntaxError: Unexpected token .
Firefox reports a slightly different message but it all points to the presence of the period (.) in the beginning of the content.
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 6 of the JSON data
I've tried both $.parseJSON() and JSON.parse() methods.
What's the cause of this error? Please enlighten.
I've read the other similar posts here, but they refer to a different character like <, etc.,
EDIT: This is the piece of code I'm using to retrieve the server data.
$.ajax({
url : searchUrl
}).done(function(data) {
var json_array = JSON.parse(data); // Apparently data is already JSON parsed.
});
That data probably is already an object, try it without $.parseJSON() or JSON.parse() and it should work.

Three.js SceneExporter getting Uncaught Syntax error

So I am trying to export a three.js scene using the SceneExporter, I am just doing this
var output = new THREE.SceneExporter().parse(scope.renderingEngine.scene);
When doing this, I get an error
Uncaught SyntaxError: Unexpected token u
Which occurs at line 750 of SceneExporter.js (which is the line where the JSON gets parsed; new THREE.SceneExporter().parse(scope.renderingEngine.scene);)
I don't have anything fancy going on in the scene, just a bunch of geometries. I even tried a scene with no textures in it and still got this error.
Now, if I change that line to simply return the output then JSON.stringify(output) and save this file, the file's JSON does not validate. I get the following error
Parse error on line 1:
"{ \n\t\"metadat
^
Expecting '{', '['
And here is line 1-10 of the JSON file
"{
\n\t\"metadata\": {
\n\t\t\"formatVersion\": 3.2,
\n\t\t\"type\"\t\t: \"scene\",
\n\t\t\"generatedBy\"\t: \"SceneExporter\",
\n\t\t\"objects\": 153,
\n\t\t\"geometries\": 144,
\n\t\t\"materials\": 5,
\n\t\t\"textures\": 1\n\t
},
\n\n\t\"urlBaseType\": \"relativeToScene\",
Anyone else having this issue?
The syntax error is a "Unexpected token: ILLEGAL" character, probably thrown by your use of "\n\t\t" and others (escape sequences) outside strings. I don't know what you are trying to achieve with escape sequences outside strings, and I don't even know if special characters should be used in JSON.
Also, I see "\" at some of your strings. You can't use "\". You can, however, use "\", that is escape sequence for a "\". Using a single "\" inside a string will give you the "Unexpected token: ILLEGAL" error. "\" must always be followed by a character that makes a valid escape sequence.

Trying to parse JSON string, unexpected number

I am trying to parse this JSON:
var json = '{"material":"Gummislang 3\/4\" 30 m (utanp\u00e5liggande sk\u00e5p)"}'
I run JSON.parse(json) but i get the error SyntaxError: Unexpected number when doing so. I have tried this in Google Chrome. I don't know what the problem is since I can take the JSON string and put it in any JSON validator and it claims that the JSON is valid. Shouldn't the browser be able to parse it?
You are inserting a JSON object representation into a JavaScript string without properly escaping the representation.
To avoid having to do this, remove the quotes you are adding around the representation, and skip the JSON.parse(json) – the default output from PHP's json_encode() is valid JavaScript when used in this context.
For security, you should specify the JSON_HEX_TAG option if possible. This will prevent cross-site scripting in cases where the JSON might end up inside a document parsed as XML. (And for XML documents, the JSON should be inside a CDATA section as well.)
You're validating the string literal, which is a valid JSON string containing invalid JSON. You need to validate the value of the string, which is not valid JSON.
If you paste the string value into a JSON validator, you'll see that the error comes from this part:
"material": "Gummislang 3/4"30m
The " needs to be escaped.

storing email-validation regex string in JSON

I have a regex string for validating email addresses, and I'd like to send it down to my application over json. I get an error from dojo/Json saying:
Uncaught SyntaxError: Unexpected token ]
So I took my JSON file and dropped it into JSONLint and got this slightly more specific error:
Parse error on line 3:
... { "regex": "^(([^<>()[\]\\.,;:\
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
Here's my json file contents:
{
"Email Address": {
"regex": "^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$"
}
}
Json.org doesn't seem to say anything about escaping regex characters...and the string itself is escaped properly because I can set a variable to that regex string in a js console.
Anyone know what I can do to get this to work?
This doesnt work because your using " within the strings.
One work around would be to replace every " with something like /'\ then what you parse it again replace every /'\ with " and that will work.
Will look in to a better way but hopefuly this helps in the mean time.
UPDATE:
Every base 64 encode it then decode it: similar to http://decodebase64.com/
And save the base 64 encode regex when your doing stringify and then when you parse decode the the base 64 and store it back..
So basicly
-when wanting to stringify
-base64 encode regex
-Overwrite normal regex with base 64
-Stringify json
-when wanting to parse JSON
- Parse it in
- Get base 64 reg ex
- Decode it
- Replace it

Categories

Resources