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
I get this data with an Ajas call. I convert the data with JSON.stringify
const jsonOrders = JSON.stringify(orders).replace(/[\/\(\)\']/g, "\\$&");
To use this data in an Adobe CEP Panel I pass the data like so:
csiRun.evalScript(`setupSwitchBlade('${jsonOrders}', '${layoutFile}', '${orderDate}', '${productTag}', 1)`);
The object is a large string with multiple items so it would be something like (just an example not valid viewed from console):
{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. I parse it like so:
var orderParsed = JSON.parse(orders);
This causes the error I get JSON.Parse error.
I tracked down the issue to this string also indicated above:
OG\'S RIDES
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?
CodePudding user response:
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" }
CodePudding user response:
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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
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"}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>