Home > Enterprise >  Convert string to json valid value
Convert string to json valid value

Time:01-14

I need to send a string to an end point that accepts data as 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'
        });

now when providing this is a text with " random text " , to test as the value of some_data the ajax request throws an error in the console but when providing this is a text with \" random text \" , to test it works fine

Is there a built-in way to convert " to \" with out writing my own function

CodePudding user response:

Why do it that way when you can do

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

Just use JSON.stringify

  •  Tags:  
  • Related