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);
Related
I am new to typescript. please help to push the data so here it goes
Here the story goes I have string array and i need to push it to the json object
interface LocalIds {
value: string;
label: string;
}
const localIds = [
{ value: 'test', label: 'test' },
{ value: 'test2', label: 'test2' },
];
////////////// HERE in string array that data is coming ///////////
const localIdentifiers: string[] = result.data.map((item: string) => item);
///////////// I want to push the string array data to json object with label & value//////
// I experimented alot but giving some type error and all I am not getting
localIds.push({ label: 'abc', value: 'abc' });
localIdentifiers.map(i => localIds.push(...localIds:{value:i,label:i}[])); //ERROR
Half of your code does nothing useful
result.data.map((item: string) => item) will do nothing
using map when not returning anything inside it is pointless. At very least use forEach instead. or even better....
You should use map with concat:
interface LocalIds {
value: string;
label: string;
}
const localIds = [
{ value: 'test', label: 'test' },
{ value: 'test2', label: 'test2' },
];
localIds.push({ label: 'abc', value: 'abc' });
const finalLocalIds = localIds.concat( result.data.map((i: string) => ({value:i,label:i})) );
Live example
Try fixing last line as following
replace ; with , and remove [] at the end
localIdentifiers.map(i => localIds.push(...localIds, {value:i,label:i}));
also, you dont need ...localIds, since it will duplicate current array every time element is pushed to array
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
}]]
How can I automate the process of assigning the key to an object from an array and the value to contain the same element as a string?
I have an empty object and an array:
const myObject= {};
const newsCategory = ['business', 'entertainment', 'general', 'health', 'science'];
I need to populate the object with key-value pairs.
The key should be each element from the newsCategory array.
The value should be an instance of another object.
new GetNews({country: 'gb', category: newsCategory[element]});
I can do this the manual way, assigning each category individually:
myObject.business = new GetNews({country: 'gb', category: newsCategory ['business']});
...and the same to the rest of the categories.
The result would be
{
business: GetNews {
category: "business"
country: "gb"
}
entertainment: GetNews {
category: "entertainment"
country: "gb"
}
general: GetNews {
category: "general"
country: "gb"
}
health: GetNews {
category: "health"
country: "gb"
}
science: GetNews {
category: "science"
country: "gb"
}
}
I need to do this process automatically, with a loop for example.
This is my attempt but it's not working.
newsCategory.forEach((category) => {
let cat = String.raw`${category}`; //to get the raw string
myObj.cat = new GetNews({country: 'gb', category: category});
})
};
/*
output:
{cat: "undefined[object Object][object Object][object Obj…ect][object Object][object Object][object Object]"}
*/
How can I automate the process of assigning the key to an object from an array and the value to contain the same element as a string?
Instead of myObj.cat you should do myObj[cat] so that cat is evaluated as the key value, otherwise you're setting a key named "cat".
Also String.raw is weird, don't use that. Your categories are strings already.
newsCategory.forEach((category) => {
myObj[category] = new GetNews({country: 'gb', category: category});
})
};
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
I am filtering and mapping the array objects that looks like this:
taxonomy:Object
data:Array[2]
0:Object
id:377
name:"Buss"
slug:"buss"
type:"post_tag"
1:Object
My function looks like this:
let tag = this.article.taxonomy.data.filter(function( data ) {
return data.type.includes('tag')
}).map(function(obj) {
return obj.name;
});
return tag;
What I am just wondering is there a way to get from the map function just the string name value, since now it returns ["Buss"], so that don't need to use the index at the end of the function:
return tag[0]
It sounds like you want find, not filter, if you're looking only for one result. find returns the first entry for which the callback returns a truthy value, or undefined if it never does. So:
const obj = this.article.taxonomy.data.find(data => data.type.includes('tag'));
const tag = obj && obj.name; // Note the guard in case no entry matched
return tag; // Will be the name or `undefined`
(Note that I've assumed you can use an arrow function, as you're using let. If not, just replace it with a function function.)
Live Example:
const taxonomy = {
data: [
{
id: 375,
name: "A",
slug: "A",
type: "nope"
},
{
id: 376,
name: "B",
slug: "B",
type: "nor-this"
},
{
id: 377,
name: "Buss",
slug: "buss",
type: "post_tag"
},
{
id: 378,
name: "C",
slug: "C",
type: "blah"
}
]
};
const obj = taxonomy.data.find(data => data.type.includes('tag'));
const tag = obj && obj.name;
console.log(tag);