JSON.parse a string with an escape - javascript

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?

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"}

Related

replace JSON object value single quote with double quote

My JSON response values have single quote but I want double quote. I have already tried JSON.stringfy() and JSON.parse(), they both are not working.
Response:
[
{
title: 'Car',
price: 2323,
}
]
Expected Response:
[
{
title: "Car",
price: 2323,
}
]
Basically, I want to use that response in shopify graphql query.
mutation {
productCreate(input: {
id:"gid://shopify/Product/4725894742116"
title: "This is a car",
variants:[{
title:"car",
price: 12
}]
}) {
product {
id
}
}
}
You can use JSON.parse() method parses a JSON string
and The JSON.stringify() method converts a JavaScript object or value to a JSON string.
let obj =[
{
title: 'Car',
price: 2323,
}
];
let result = JSON.parse(JSON.stringify(obj));
console.log(result);
the result is
[
{
title: "Car",
price: 2323,
}
]
I don't see, any problem using JSON.stringify you can either get the string directly and use it inside a query or if you need a javascript object, you can just parse it.
JSON.Stringify
JSON.parse
Passing arguments in GraphQl
const unwantedResponse = [{
title: 'Car',
price: 2323,
}]
const wantedResponse = JSON.stringify(unwantedResponse);
const parsedResponse = JSON.parse(wantedResponse)
console.log(wantedResponse);
console.log(parsedResponse);
You could apply: JSON.stringify (which converts a JS object to a JSON string), then JSON.parse (which parses a JSON string back to a JS object), e.g.
let x = [{
title: 'Car',
price: 2323,
}];
x = JSON.parse(JSON.stringify(x));
console.log(x);

Can valid JSON file consist of only one single object's description?

Example of given JSON file is as follows:
result = {
"name": "Foo",
"id": "10001",
"values": "1,2,3,4"
};
No, that is not valid JSON.
First, JSON is a string. What you have in the question is a JavaScript object literal expression assigned to the variable result.
Go to https://jsonlint.com/ , paste your file into the box, and click Validate. You will see the following output:
Error: Parse error on line 1:
result = { "name":
^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
As you can see from the JSON specification , you can't have a variable as a top-level entity. The valid entities in a JSON string are:
a string
an object
an array
a number
Your result variable is not one of those things. It's a variable, which is only valid in JavaScript.
objLiteral = {
"name": "Foo",
"id": "10001",
"values": "1,2,3,4"
};
jsonString = '{ "name": "Foo", "id": "10001", "values": "1,2,3,4" }';
var myObj = JSON.parse( jsonString );
console.log(objLiteral);
console.log(myObj);
console.log(objLiteral.name);
console.log(myObj.name);
<pre>Sample javascript</pre>

Json to javascript dictionary

I have JSON data in the following structure, and I'm trying to parse it in order to work with the data using javascript.
JSON Data
{
"FirstItem": {
"id": 1,
"type": "foo",
"colours": ["blue", "black", "green"],
"reviews": {
"positive": ["The best", "unbelievable", "Awesome"],
"negative": ["Sh*t", "Awful", "Dire", "Terrible", "Appalling"],
"neutral": ["OK", "Meh"]
}
},
"SecondItem": {
"id": 2,
"type": "bar",
"colours": ["red", "white", "yellow"],
"reviews": {
"positive": ["Great", "Amazing", "Fantastic", "Perfect", "Uplifting"],
"negative": ["Terrible", "Shocking", "abysmal"],
"neutral": ["OK", "Standard", "Vanilla"]
}
}
}
I am trying to parse this using JSON.parse(), however this returns the following error:
JSON.parse: unexpected character at line 1 column 2 of the JSON data
I have previously worked with this same JSON structure using C#, and had to deserialise this into a dictionary - information can be found on this post
Question
How can I parse this JSON into a javascript object, which will allow me to loop and evaluate each item?
JSON is Javascript Object with double quoted key like what you have in sample. So you don't need to parse it again, see this for explanation. You can access data from it using its key or if in case you want to get reviews from SecondItem, you can access it with :
SecondItem.reviews
or
SecondItem['reviews']
Apparently you are trying to parse an already parsed object
x = {A:1}; // A javascript object
JSON.parse(x); // Error
this happens because JSON.parse will convert the object to a string first, getting "[object Object]" and then will try to parse this string.

How to write proper string to work with JSON.parse

I've got a problem with my node.js application.
I'm trying to parse string using JSON.parse like this:
try{
skills = JSON.parse(user.skills);
}catch(e){
console.log(e);
}
In user.skills I've got such a string:
"[ { name: Dreamweaver, level: 60 }, { name: Phototshop, level: 80 }]"
and it throws me: [SyntaxError: Unexpected token n].
Can anybody help me?
Thanks in advance :)
Your JSON data is incorrect. There should be quotes "" around strings.
should be like this
var str = "[ { \"name\": \"Dreamweaver\", \"level\": 60 }, { \"name\": \"Phototshop\", \"level\": 80 }]"
If you want to see how should be a proper JSON String Try this
var data = {name:"mark"}
JSON.stringify(data) //returns "{"name":"mark"}" Here you have to care about escaping quotes.
JSON data needs identifiers and values to be strings, try this:
'[ { "name": "Dreamweaver", "level": "60" }, { "name": "Phototshop", "level": "80" }]';
You can use http://jsonlint.com/ to varify json. After that we can stringify and parse json respectively.

What is the correct format of populating a JSON object with a nested array of objects?

I'm trying to create a JSON object with a nested array of JSON objects. What is the correct format of this?
Here is an example what I am trying to create:
{
"reviewCount": 96,
"reviews": [
{"name": "Sean Steinman", "date": "reviewed 2 weeks ago", "reviewContent": "Fantastic Service"},
{"name": "Ryan Lundell", "date": "reviewed in the last week", "reviewContent":"Ask for Scott!"}
]
}
Here is what I have so far:
var reviewObj = {
reviewCount: reviews.length,
reviews: [{name: , date: , reviewContent:}]
}
After I initialize it, I will fill it with a for loop that runs through an existing array of strings.
CLARIFICATION:
The array that I'm using to populate the JSON object is:
[
"\nSean Steinman\nreviewed 2 weeks ago\n Fantastic Service\n",
"\nRyan Lundell\nreviewed in the last week\n Ask for Scott!\n• • •\n"
]
So I'm creating a new array in my for with tmpArr = reviews[i].split('/n');, and then where I'm getting stuck is how to stick that into the JSON object as an object.
First, you're not building a "JSON" object. You're just building an object. It's not JSON until you JSON-encode it. {"name": "bob"} is not JSON, it's an object literal. '{"name": "bob"}', the string, is JSON.
Second, you cannot loop inside an object literal, which is what your second code example seems to indicate you're trying to do. Instead, you need to initialize you reviews property to an empty array, and then loop and append items to the array.
var reviews = [
"\nSean Steinman\nreviewed 2 weeks ago\n Fantastic Service\n",
"\nRyan Lundell\nreviewed in the last week\n Ask for Scott!\n• • •\n"
];
var reviewObj = {
reviewCount: reviews.length,
reviews: []
}
reviews.forEach(function(line) {
var review = line.split("\n");
reviewObj.reviews.push({name: review[0], date: review[1], reviewContent: review[2]});
});

Categories