用双引号替换JSON对象值单引号

时间:2020-06-06 15:31:08

标签: javascript node.js json

我的JSON响应值具有单引号,但我想要双引号。我已经尝试过JSON.stringfy()JSON.parse(),它们都无法正常工作。

回复:

[
  {
    title: 'Car',
    price: 2323,
  }
]

预期的响应:

[
  {
    title: "Car",
    price: 2323,

  }
]

基本上,我想在shopify graphql查询中使用该响应。

mutation {

    productCreate(input: {
      id:"gid://shopify/Product/4725894742116"
      title: "This is a car",
        variants:[{
        title:"car",
        price: 12
        }]
    }) {
      product {
        id
      }
    }
  }

3 个答案:

答案 0 :(得分:3)

我没有看到,使用JSON.stringify会出现任何问题,您可以直接获取字符串并在查询中使用它,或者如果需要javascript对象,则可以对其进行解析。

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);

答案 1 :(得分:3)

您可以使用JSON.parse()方法解析JSON字符串 JSON.stringify()方法将JavaScript对象或值转换为JSON字符串。

let obj =[
  {
    title: 'Car',
    price: 2323,
  }
];

let result = JSON.parse(JSON.stringify(obj));



console.log(result);

结果是

[
  {
    title: "Car",
    price: 2323,

  }
]

答案 2 :(得分:2)

您可以应用:JSON.stringify(将JS对象转换为JSON字符串),然后应用JSON.parse(将JSON字符串解析回JS对象), eg

let x = [{
  title: 'Car',
  price: 2323,
}];
x = JSON.parse(JSON.stringify(x));
console.log(x);

相关问题