javascript 我想删除变量中的双引号

ttisahbt  于 2023-02-21  发布在  Java
关注(0)|答案(2)|浏览(183)
var aProd = "{'name':'Product One','description':'Description Product One','unit_amount':{'currency_code':'USD','value':'247','sku':'h545'},'quantity':'1'}";

var item = new Array(aProd);
  console.log(item);

结果这

[
    "{'name':'Product One','description':'Description Product One','unit_amount':{'currency_code':'USD','value':'247','sku':'h545'},'quantity':'1'}"
]

如何删除双引号?
到这个

[
    {'name':'Product One','description':'Description Product One','unit_amount':{'currency_code':'USD','value':'247','sku':'h545'},'quantity':'1'}
]

已经试过了
变量项=新数组(字符串(ci). replace(/"/g,""));

变量项= ci.到字符串().替换(/"/g,"");
但我不能去掉双引号

dohp0rv5

dohp0rv51#

使用JSON.parse(将所有单引号转换为双引号后):

let aProd = "{'name':'Product One','description':'Description Product One','unit_amount':{'currency_code':'USD','value':'247','sku':'h545'},'quantity':'1'}";
let res = [JSON.parse(aProd.replaceAll("'", '"'))];
console.log(res);
2g32fytz

2g32fytz2#

这听起来像是要创建一个数组,并将该数据作为其第一个对象,现在,该数据不是有效的JSON,因此需要首先将所有单引号替换为双引号,解析它,然后将其括在[]大括号中。

const aProd = "{'name':'Product One','description':'Description Product One','unit_amount':{'currency_code':'USD','value':'247','sku':'h545'},'quantity':'1'}";

// Replace the single quotes with double quotes
const json = aProd.replaceAll("'", '"');

// Parse the now-valid JSON, and place it in an array
const arr = [JSON.parse(json)];

// Here's your new data structure
console.log(arr);

// And here, and an example, we log the value
// of `name` from the object which is the
// first `[0]` element of the array
console.log(arr[0].name);

相关问题