gpt4 book ai didi

javascript - 使用反斜杠转义双引号

转载 作者:行者123 更新时间:2023-12-01 00:17:20 26 4
gpt4 key购买 nike

我有一个对象:

const ratingSettings = {performer: true, chiefEngineer: true, engineer: true, customer: true}

我想将其转换为 GraphQL 字符串,类似于用反斜杠转义所有双引号:

"{\"performer\":true,\"chiefEngineer\":true,\"engineer\":true,\"customer\":true}"

我尝试了以下方法:

const ratingSettings = JSON.stringify({performer: true, chiefEngineer: true, engineer: true, customer: true})

const getMutationObject = data => Object.keys(data).map(key => `${key}: "${data[key]}"`).join(' ')

const userData = getMutationObject(ratingSettings);

但我得到的并不完全是我需要的:

"{"performer":true,"chiefEngineer":true,"engineer":true,"customer":true}"

我需要用\转义所有双引号

提前感谢您提供的解决方案!

最佳答案

JSON.stringify 对象,然后使用 .replace 将所有 " 替换为 \\" :

const ratingSettings = {performer: true, chiefEngineer: true, engineer: true, customer: true}
const escapedJSON = JSON.stringify(ratingSettings)
.replace(/"/g, '\\"');
console.log(escapedJSON);

关于javascript - 使用反斜杠转义双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59678213/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com