Convert an array in string format to javascript array - javascript

I have an array which is in string format,
var str = {
id: 123,
changes: "[[atr:test1, old:null, new:null], [atr:messageText, old:test here, new:hello test], [atr:status, old:null, new:1]]"
}
var d = str.changes
I tried to convert the 'changes' array from string format using different methods by combining split(), replace(), slice() etc...and even JSON.parse(), but nothing worked.
Is there any way to convert this into javascript array?

Note that the string is not valid anything but string.
It is not a valid array, and the string is not valid JSON.
If you can, get the server to change it to the valid JSON string
"[{\"atr\":\"test1\", \"old\":null, \"new\":null}, {\"atr\":\"messageText\", \"old\":\"test here\", \"new\":\"hello test\"}, {\"atr\":\"status\", \"old\":null, \"new\":1}]"
If the response is ALWAYS on the format you gave, then you can create valid JSON
var str = {
id: 123,
changes: "[[atr:test1, old:null, new:null], [atr:messageText, old:test here, new:hello test], [atr:status, old:null, new:1]]"
}
// change the inner [ ] to { }
let changes = str.changes.replace(/\[\[/g, "[{").replace(/\], \[/g, "},{").replace(/\]\]/g, "}]")
// change the unquoted keys and values to quoted keys and values
changes = changes.replace(/(\w+):/g, '"$1":').replace(/:([\w ]+)([},])/g, ':"$1"$2')
// parse the object
changes = JSON.parse(changes);
// replace "null" with null - could have been done above bt the regex would be nasty
changes.forEach(item => Object.keys(item).forEach(key => item[key] = item[key] === "null" ? null : item[key]))
console.log(changes)

I think the problem is that the key 'changes' do not any valid JSON. You can validate, format it here.
If there is a valid JSON in 'changes' key, It can be converted to Js array using JSON.parse();, Something like:
var str = { id: 123,
changes: `[
[
{
"atr": "test1",
"old": null,
"new": null
}
],
[
{
"atr": "messageText",
"old": "test here",
"new": "hello test"
}
],
[
{
"atr": "status",
"old": null,
"new": 1
}
]
]`
}
var d = JSON.parse(str.changes);
console.log(d);
//str.changes Object:
[[[object Object] {
atr: "test1",
new: null,
old: null
}], [[object Object] {
atr: "messageText",
new: "hello test",
old: "test here"
}], [[object Object] {
atr: "status",
new: 1,
old: null
}]]

Related

Stringify and parse complex object with nested arrays from localStorage

I have a very complex dictionary object consisting of very deeply nested combinations of objects and arrays.
I use a custom deepCopyObject function to make a deep copy of my object throughout my code. That works fine, I'm only including it because it's the only way I'm able to copy the object without a shallow reference.
The issue comes when I try to store and retrieve it from localStorage with parse and stringify. The below code returns:
nextQuestion local_user_dict is [object Object]
test.html:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
The code below was structured by copying the object from the console in the browser and editing the keys/values. I left all of the structure intact including the "null" values which I didn't include but I assume is due to it being an array nested within the object.
I'm told that stringify and parse should work with deeply nested and complex objects including with arrays (Though I've read elsewhere online that's not true). How can I correctly pass this object and retrieve it from localStorage?
If I use my deep copy function on the object it works fine and displays as it should, the problem only occurs when stringifying and parsing from localStorage.
var test_dict = {
"questions": {
"obj1": {
"words": [
null,
{
"test1": {
"test2": "test7",
"test3": "test6"
},
"test4": "test5"
},
{
"test8": {
"test9": 0,
"test10": "2",
},
"test11": [
null,
{
"test12": {
"no": 0,
"yes": 1
},
"test13": "test14"
},
{
"test15": {
"no": 0,
"yes": 1
},
"test16": "test17"
},
{
"test18": {
"no": 0,
"yes": 1
},
"test19": "test20"
}
]
}
]
}
}
}
localStorage.setItem('user_dict', deepCopyObject(test_dict))
let local_user_dict = localStorage.getItem('user_dict')
console.log('nextQuestion local_user_dict is ', local_user_dict)
let parsed_local_user_dict = JSON.parse(local_user_dict)
console.log('nextQuestion parsed_local_user_dict is ', parsed_local_user_dict)
user_dict = deepCopyObject(parsed_local_user_dict)
console.log('nextQuestion user_dict is ', user_dict)
function deepCopyObject(inObject) {
let outObject, value, key
if (typeof inObject !== "object" || inObject === null) {
return inObject
}
outObject = Array.isArray(inObject) ? [] : {}
for (key in inObject) {
value = inObject[key]
outObject[key] = deepCopyObject(value)
}
return outObject
}
localstorage stores strings. not objects.
change
localStorage.setItem('user_dict', deepCopyObject(test_dict))
to
localStorage.setItem('user_dict', JSON.stringify(test_dict))
and ditch the copy. you can actually use JSON parse and stringify to copy objects.

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>

convert return object to json but only certain value pairs

Yes I know there are heaps of posts about converting objects to json but my question is more specific..
Say Im calling some data from an api and the response is an object that looks like this
{
date: ...,
value: ...,
useless-info: ...,
useless-info: ...
}
now I know I can do this JSON.stringify(returnedobject);
so I get the newly formed json..
{
"date": ...,
"value": ...,
"useless-info": ...,
"useless-info": ...
}
now all I want in my newly formed json to be the "date" and "value" and remove the useless-info is this even possible?
any help would be appreciated!
Working Demo
var jsonObj = {
"date": "",
"value": "",
"useless-info": "",
"useless-info": ""
};
delete jsonObj["useless-info"];
var jsonString = JSON.stringify(jsonObj);
console.log(jsonString);
JSON.stringify() has a replacer param that can be used to limit output to a whitelisted array of keys you want to keep.
// Input.
const input = {
date: new Date(),
value: 8905934,
useless: 'useless',
extra: 'extra'
}
// Output.
const output = JSON.stringify(input, ['date', 'value'])
// Proof.
console.log(output)
const oldJson = {
"date": ...,
"value": ...,
"useless-info": ...,
"useless-info": ...
}
const newJson = {
"date" : oldJson.date,
"value": oldJson.value
}
You can either create a new object with the data you want, or delete the fields you don't need:
const someReturn = {
date: ...,
value: ...,
badstuff: ...
}
const goodObj = {
date: someReturn.date,
value: someReturn.value
}
Or to delete fields you can just call delete someReturn.badstuff

Parsing string json in javascript throws Unexpected token

var filter1 = " { where:{ businessName:{ $like:'%A'} ,'userId': { $gt: 0} }, limit: 1 }"
I want to make pass it like this JSON
var filter = { where:{ businessName:{ $like:'%A'} ,'userId': { $gt: 0} }, limit: 1 }
I did this to make it like JSON example.
JSON.parse(filter)
But it throws the following exception:
SyntaxError: Unexpected token w in JSON at position 3
Your JSON is not valid. Use "" with all keys and for values, except numbers and bools
var filter1 = '{ "where": { "businessName" :{ "$like":"%A"} ,"userId": { "$gt": 0} }, "limit": 1 }'
var filter1 = '{ "where": { "businessName" :{ "$like":"%A"} ,"userId": { "$gt": 0} }, "limit": 1 }';
var filter = JSON.parse(filter1);
console.log(filter);
It's not valid JSON string. It's more a JavaScript object literal wrapped in quotes.
In JSON standard all keys should be wrapped in quotes, so here is how your JSON would look like:
"{"where":{"businessName":{"$like":"%A"},"userId":{"$gt":0}},"limit":1}"
Since your string is simply a JavaScript object wrapped in quotes, you can arrive at the correct JSON string by simply removing quotes:
var filter1 = { where:{ businessName:{ $like:'%A'} ,'userId': { $gt: 0} }, limit: 1 }
and running it through JSON.stringify:
JSON.stringify(filter1);

Categories