简体   繁体   中英

JSON.parse a string with an escape

Currently I am attempting to parse a long object with JSON.Parse The object contains a lot of data but specifically this is causing an issue:

OG\'S RIDES

The object is a large string with multiple items so it would be something like:

{id: 113592, order_number: "204736", internal_order: "204736-0", order_date: "11-15-2021", custom1: "OG\'S RIDES"}

The entire object is being passed as a string and then I have to parse it.
This causes the error I get JSON.Parse error.

As you can see the cause of the issue is being escaped but I still get the error. Any idea how I can solve this?

The error is that JSON format Expecting 'STRING'!

{id: 113592, order_nu
-^

So surround properties with double quotes "

{"id": 113592, "order_number":...}

with a readable format:

const json = `{
  "id": 113592,
  "order_number": "204736",
  "internal_order": "204736-0",
  "order_date": "11-15-2021",
  "custom1": "OG'S RIDES"
}`
console.log(JSON.parse(json))
//JAVASCRIPT Object:
//{ id: 113592, order_number: "204736", internal_order: "204736-0", order_date: "11-15-2021", custom1: "OG'S RIDES" }

I think the problem is that your properties must be quoted for it to be valid JSON. Don't confuse JavaScript Object Notation (JSON) with JavaScript. :)

 input = `{"id": 113592, "order_number": "204736", "internal_order": "204736-0", "order_date": "11-15-2021", "custom1": "OG\\'S RIDES"}` result = JSON.parse(input) console.dir(result);

The object that you get is not a valid stringified object. So To fix your issue, you have to stringify the object first and parse it again.

 const object = JSON.stringify({id: 113592, order_number: "204736", internal_order: "204736-0", order_date: "11-15-2021", custom1: "OG\\'S RIDES"}); // `{"id":113592,"order_number":"204736","internal_order":"204736-0","order_date":"11-15-2021","custom1":"OG'S RIDES"}` const data = JSON.parse(object); // {id: 113592, order_number: '204736', internal_order: '204736-0', order_date: '11-15-2021', custom1: "OG'S RIDES"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM