将字符串转换为 json 有效值

Convert string to json valid value

我需要将字符串发送到接受数据的端点 JSON

    data = '{"data":"'+some_data+'"}';
    $.ajax({
        type: 'POST',
        url: "example.com/endpoint",
        data: data, 
        success: function(data) { console.log('data: ' + data); },
        contentType: "application/json",
        dataType: 'json'
        });

现在,当提供 this is a text with " random text " , to test 作为 some_data 的值时,ajax 请求会在控制台中抛出错误 但是当提供 this is a text with \" random text \" , to test 时它工作正常

是否有一种内置方法可以将 " 转换为 \" 而无需编写我自己的函数

既然能做到,为什么要那样做

let data = {data: ' this is a text with " "  ' };
data = JSON.stringify(data);        
console.log(data);

只需使用JSON.stringify