0

I have the following valid json (partially shown), which I have received as a response to an HTTP request (I don't control the server):

"TotalResults":2,"SearchTerm":"XX","SearchTermClean":"XX","SearchTermExact":"\"XX\"","SearchTermNonExact":"XX","Page":1,"PageSize":100,"TotalPages":1,"TotalTime":0.072,"Filter":"","Sort":"","SortClean":"","IsDesc":false,"PreviousPage":1,"NextPage":1}'

I'm trying to parse this JSON using:

var json_obj= JSON.parse(helpers.testJSON());

where testJSON returns an entire string of json.

I'm getting:

Uncaught SyntaxError: Unexpected token X in JSON at position 1685

which translates to:

":"\"XX\""

How can I fix this error? I assume I would need to preprocess the JSON before using JSON.parse

user1592380
  • 34,265
  • 92
  • 284
  • 515
  • 3
    Two things, what's with the blockquotes? And the object syntax you showed doesn't start with a `{`. – Taplar Dec 23 '20 at 18:21
  • 3
    But `:""XX""` is not valid JSON. The inner double quotes should be escaped. `:"\"XX\""` – Taplar Dec 23 '20 at 18:22
  • 1
    Does this answer your question? [How to escape double quotes in JSON](https://stackoverflow.com/questions/15637429/how-to-escape-double-quotes-in-json) – evolutionxbox Dec 23 '20 at 18:28
  • 1
    You should really properly format the code block within your question. At the moment, it is unclear whether your JSON is invalid or you have just omitted a portion. – MC Emperor Dec 23 '20 at 18:31
  • 1
    In order to do so, start your code block with triple backticks (`\`\`\``), optionally followed by the language identifier (in your case `json`) to enable syntax highlighting. End the block also with triple backticks. – MC Emperor Dec 23 '20 at 18:35
  • Thanks everyone, Using the backticks is making the json look correct. – user1592380 Dec 23 '20 at 18:53

1 Answers1

1

There is an error in your example. You are using double quotes inside the string. To fix this, you need to escape them with \

So your JSON will look like this:

{
   "Results":2,
   "SearchTerm":"XX",
   "SearchTermClean":"XX",
   "SearchTermExact":"\"XX\"",
   "SearchTermNonExact":"XX",
   "Page":1,
   "PageSize":100,
   "TotalPages":1,
   "TotalTime":0.072,
   "Filter":"",
   "Sort":"",
   "SortClean":"",
   "IsDesc":false,
   "PreviousPage":1,
   "NextPage":1
}

For easy detection of errors in JSON syntax, beautify and other useful actions, you can use this tool

xom9ikk
  • 2,159
  • 5
  • 20
  • 27
  • If this is the answer (I think it is) then the question is a duplicate of https://stackoverflow.com/questions/15637429/how-to-escape-double-quotes-in-json – evolutionxbox Dec 23 '20 at 18:43