在 JavaScript 中,如果你想去掉 JSON 字符串中的双引号,可以使用多种方法。以下是一些常见的方法和示例代码:
JSON.parse
和 JSON.stringify
这种方法适用于你有一个 JSON 字符串,并且你想将其转换为一个 JavaScript 对象,然后再将其转换回一个没有双引号的字符串。
const jsonString = '{"name":"John", "age":30, "city":"New York"}';
// 解析 JSON 字符串为 JavaScript 对象
const jsonObj = JSON.parse(jsonString);
// 将 JavaScript 对象转换为没有双引号的字符串
const result = JSON.stringify(jsonObj, null, 2).replace(/"/g, '');
console.log(result);
如果你只想简单地去掉 JSON 字符串中的所有双引号,可以使用正则表达式。
const jsonString = '{"name":"John", "age":30, "city":"New York"}';
// 使用正则表达式去掉所有双引号
const result = jsonString.replace(/"/g, '');
console.log(result);
replace
方法这种方法类似于方法二,但更具体地针对 JSON 字符串中的键和值。
const jsonString = '{"name":"John", "age":30, "city":"New York"}';
// 使用 replace 方法去掉所有双引号
const result = jsonString.replace(/"(\w+)":/g, '$1:').replace(/:(\w+),/g, ':$1,');
console.log(result);
希望这些方法能帮助你解决问题!如果有其他问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云