JSON Parse with square brackets inside data - javascript

I am trying to parse a JSON string which contains square brackets inside the string.
For example
"[[\"hello\", \"i\", \"like [cows]\"], [\"what\", \"about [you]?\"]]"
It shows an error while parsing:
Uncaught SyntaxError: Unexpected token [
How can I parse the string anyway while leaving the brackets as they are?

I found the problem. I needed to use addslashes() around the strings in the PHP code which serves the code. There was a part of a string containing [C:\].

I see in your later comments that you're creating this JSON string within PHP. You should encode the JSON data within PHP using json_encode, as shown here:
http://www.dyn-web.com/tutorials/php-js/json/array.php
It should then come out in a format that you can JSON.parse.

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

JSON coming from server with quotes and regular expression

I'm analysing the way a server of a search page works (by inspecting element) and I could conclude that the request is sent with a POST with JSON as parameters.
Then I simulated the same POST (with the same parameters) using Insomnia. It was successful, but the response JSON came as string and inside the JSON, variables that uses quotes now uses \" instead.
An example of the JSON response:
"{\"AudienceRefiner\":{\"ItemCount\":0}}"
How can I read this on Python?
It is just an escape character, Consider using the ast library in order to parse it into an object.
literal_eval:
Safely evaluate an expression node or a Unicode or Latin-1 encoded
string containing a Python literal or container display.
import ast
st = "{\"AudienceRefiner\":{\"ItemCount\":0}}"
obj = ast.literal_eval(st)
print (obj)
>>> {'AudienceRefiner': {'ItemCount': 0}}
For more information about it, read ast.literal_eval
I am not sure where you got "{\"AudienceRefiner\":{\"ItemCount\":0}}" I guess that its not is python but webbrowser. Anyhow just use json if the json is in a string object
import json
di = json.loads("{\"AudienceRefiner\":{\"ItemCount\":0}}")

Javascript eval fails on complicated json array [duplicate]

This question already has answers here:
JSON Javascript escape
(4 answers)
Closed 7 years ago.
I want to convert a json string to object by eval, but it fails with error like:
Uncaught SyntaxError: Unexpected identifier VM250:1
below is my string:
'[{"quiz_id":"3","_id":"1","option_in_json":"[{\"option\":\"1\",\"is_answer\":false},{\"option\":\"2\",\"is_answer\":true}]","question":"1+1"}]';
Seems there is something wrong in the bold part, but i don't know how to fix it
The code below is not working
var m='[{"quiz_id":"3","_id":"1","option_in_json":"[{\"option\":\"1\",\"is_answer\":false},{\"option\":\"2\",\"is_answer\":true}]","question":"1+1"}]';
eval(m);
The code below is working so i think the data structure of this json string is ok
var m=[{"quiz_id":"3","_id":"1","option_in_json":"[{\"option\":\"1\",\"is_answer\":false},{\"option\":\"2\",\"is_answer\":true}]","question":"1+1"}];
alert(m[0].option_in_json);
Also tried with $.parseJSON with no luck
It does not work because you are not escaping the data inside the string literal correctly. Look at the value of m in the first case, especially the quotation marks:
[{"option_in_json":"[{"option":"1","is_answer":false}]","question":"1+1"}]
// ^ ^
I removed some irrelevant data. You should be able to see that this cannot be valid JavaScript (or JSON), because the quotation mark before option terminates the string.
In order to put the data inside a string literal, you should either fix the data so that it doesn't contain nested JSON, or escape \:
'[{"option_in_json":"[{\\"option\\": ... }]"}]'
Better of course if you are not putting it in a string literal in the first place.
var m='[{"quiz_id":"3","_id":"1","option_in_json": [{"option":"1","is_answer":false},{"option":"2","is_answer":true}],"question":"1+1"}]';
// ^-- don't wrap in "" so no need to escape inner double quotes.
console.dir(JSON.parse(m));

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.

JSON array syntax. Are the curly brackets (object syntax) strictly necessary?

Is it possible for a json string to include only square brackets ? For ex. :
[["state","accepted"],["r_by_uid",1]]
I get unexpected character error from parsing that string ... (long time since i worked on this script and i think it worked before ) .
Parsing the json string will allways make an object from the string ? or is it possible to parse the string into an array ?
Basically i just want to parse the string into an array , not an object .
I googled some examples but couldnt find any example that is using only square brackets.
As requested here is the tag that holds the json string :
<button data-fproc='[["state","accepted"],["r_by_uid","1"]]' class="request_state_button">
Curly brackets are not strictly necessary.
[["state","accepted"],["r_by_uid",1]] is valid JSON.
A JSON text can be an object or an array.
See http://json.org/ and the JSON Grammar section in https://www.ietf.org/rfc/rfc4627.txt
You can validate your JSON at http://jsonlint.com/
In Javascript, JSON.parse() returns an array:
JSON.parse('[["state","accepted"],["r_by_uid",1]]')
// result [["state", "accepted"], ["r_by_uid", 1]]
Notice that Arrays are also objects in Javascript.
It works with jQuery.parseJSON() too:
jQuery.parseJSON('[["state","accepted"],["r_by_uid",1]]')
// result [["state", "accepted"], ["r_by_uid", 1]]
Probably this will explain your problem:
var aAsArray = [["state","accepted"],["r_by_uid",1]];
var aAsString = '[["state","accepted"],["r_by_uid",1]]';
​JSON.parse(aAsArray);​​​ //Uncaught SyntaxError: Unexpected token ....
JSON.parse(aAsString);

Categories

Resources