JavaScript json.parse string error - javascript

I want to parse this string to an array
var string= "['one','two']";
var result= JSON.parse(string);
It throws an error
`Unexpected token ' in JSON at position 1'
I believe my approach is right I just can't figure out why its throwing that error.

You should use double quotes:
var string = '["one", "two"]';
You can't use single quote in a JSON string.

Just make it like this
var string= '["one","two"]';
var result= JSON.parse(string);
Json standard requires that the string have double quotes inside.

Related

Why JSON.parse fails with this array-like string

I tried to JSON parse this
let string = `["\"test1, "\"test2"]`;
let array = JSON.parse(string);
console.log(array[0]);
It's fairly simple enough but I don't understand what's error message is supposed to tell
Uncaught SyntaxError: Unexpected token t in JSON at position 3
you are using template string to create a string.
it doesnt need a escape character for double quotes ".
type this:
let string = `["test1", "test2"]`;
let array = JSON.parse(string);
console.log(array[0])
you need a escape character for " only when you are using normal string. like this:
let string = "[\"test1\", \"test2\"]";
let array = JSON.parse(string);
console.log(array[0])
im not good at english.hope useful

Javascript - Parse a stringified arrays of strings

I have a string like so :
a= "['url1','url2','url3']"
coming from the server I want to convert it to array like :
arr = ["url1","url2","url3"]
but JSON.parse does not seems to be working and gives following error:
SyntaxError: Unexpected token ' in JSON at position 1
Thanks in advance.
You need to replace the single quotes with double quotes. An easy way to achieve this can be by replacing them with escaped quotes like this:
let validJSON = a.replace(/'/g, "\"")
JSON.parse(validJSON)
Your string needs to be in single quotes for JSON.parse to work in this example, also string representation in json uses double quotes as per standard.
JSON.parse('["url1","url2","url3"]')
Try to use this code:
a = "['url1','url2','url3']"
urls = a.split(',')
arr = urls.map(url => url.replace(/'|\[|\]/g, ''))
console.log(arr) // ["url1", "url2", "url3"]
https://jsfiddle.net/z1frh8ys/

How do JSON.parse() and escape characters work in JavaScript?

Suppose I have an object variable:
var obj = {
key: '\"Hello World\"'
}
Then I tried parse it to string by using JSON.stringify in Chrome devtools console:
JSON.stringify(obj) // "{"key":"\"Hello World\""}"
I get the result "{"key":"\"Hello World\""}". Then I give it to a string
var str = '{"key":"\"Hello World\""}'
At least I try to convert it back to obj:
JSON.parse(str);
but the browser tell me wrong Uncaught SyntaxError
What confused me is why this is wrong? I get the string from an origin object and I just want turn it back.
How can I fix this problem? If I want do the job like convert obj to string and return it back, how can I do?
You're tried to convert your JSON into a string literal by wrapping it in ' characters, but \ characters have special meaning inside JavaScript string literals and \" gets converted to " by the JavaScript parser before it reaches the JSON parser.
You need to escape the \ characters too.
var str = '{"key":"\\"Hello World\\""}'
That said, in general, it is better to not try to embed JSON in JavaScript string literals only to parse them with JSON.parse in the first place. JSON syntax is a subset of JavaScript so you can use it directly.
var result = {"key":"\"Hello World\""};
try:
var str = '{"key":"\\"Hello World\\""}';

How to parse HTML string using JSON.parse() in JavaScript?

I have an ASP.NET MVC application returning a JSON string to the VIEW.
// Parsing the model returned on the VIEW
var jsonString = '#Html.Raw(Model.ToJson())';
var jsonObj = JSON.parse(jsonString);
The problem is that I am not able to parse because the jsonString contains characters such as "\" and "'".
//Sample string
{ "description" : "<p>Sample<span style=\"color: #ff6600;\"> Text</span></strong></p>" }
JSON is valid JavaScript, so you can just do this:
var jsonObj = #Html.Raw(Model.ToJson());
FYI, the reason the JSON parsing is failing is because the although the " are escaped with \ to make it valid JSON, the backslashes themselves need escaping in the string for them to be seen by the JSON parser. Compare:
JSON.parse('"quote: \""'); // error: unexpected string
JSON.parse('"quote: \\""'); // 'quote: "'
This example should also clarify what's happening to the backslashes:
var unescaped = '\"', escaped = '\\"';
console.log(unescaped, unescaped.length); // '"', 1
console.log(escaped, escaped.length); // '\"', 2
If you want to create a valid Javascript string, you need to escape backslashes and apostrophes:
var jsonString = '#Html.Raw(Model.ToJson().Replace("\\", "\\\\").Replace("'", "\\'"))';
There you go:
using Newtonsoft.Json;
JsonConvert.SerializeObject(your html string here);

Convert array formatted strings to object

I got
[[["汽車","car","Qìchē",""]],[["名詞",["汽車","車","轎車","車輛","車廂"],[["汽車",["car","automobile","auto"],,0.26497361],["車",["car","vehicle","lathe","machine","rook","turn"],,0.21967085],["轎車",["car","bus"],,0.020115795],["車輛",["vehicle","car"],,0.013611027],["車廂",["car"],,0.0042828997]]]],"en",,[["汽車",[4],0,0,1000,0,1,0]],[["car",4,[["汽車",1000,0,0],["車",0,0,0],["轎車",0,0,0],["車輛",0,0,0],["車廂",0,0,0]],[[0,3]],"car"]],,,[["en"]],27]
this from google translator
However I tried
JSON.parse(xhr.responseText);
It return an error Unexpected token
The problem is that this string contains multiple commas making your json invalid.
You could try to replace it for a single one before parsing
var x = '[[["汽車","car","Qìchē",""]],[["名詞",["汽車","車","轎車","車輛","車廂"],[["汽車",["car","automobile","auto"],,0.26497361],["車",["car","vehicle","lathe","machine","rook","turn"],,0.21967085],["轎車",["car","bus"],,0.020115795],["車輛",["vehicle","car"],,0.013611027],["車廂",["car"],,0.0042828997]]]],"en",,[["汽車",[4],0,0,1000,0,1,0]],[["car",4,[["汽車",1000,0,0],["車",0,0,0],["轎車",0,0,0],["車輛",0,0,0],["車廂",0,0,0]],[[0,3]],"car"]],,,[["en"]],27]'
.replace(/,{2,}/g, ",") // 2 or more replace for 1
JSON.parse(x);
Or if you have access to whatever is sending this string fix the output.
First you should remove an extra [] brackets by replacing that.
ex,
[["汽車","car","Qìchē",""]]
should be:
["汽車","car","Qìchē",""]
EDIT: you can refer to this answer: Parse Google Translate Json C#
You should try:
var str = '[[["汽車","car","Qìchē",""]],[["名詞",["汽車","車","轎車","車輛","車廂"],[["汽車",["car","automobile","auto"],,0.26497361],["車",["car","vehicle","lathe","machine","rook","turn"],,0.21967085],["轎車",["car","bus"],,0.020115795],["車輛",["vehicle","car"],,0.013611027],["車廂",["car"],,0.0042828997]]]],"en",,[["汽車",[4],0,0,1000,0,1,0]],[["car",4,[["汽車",1000,0,0],["車",0,0,0],["轎車",0,0,0],["車輛",0,0,0],["車廂",0,0,0]],[[0,3]],"car"]],,,[["en"]],27]';
var objstr = $.parseJSON(str);

Categories

Resources