jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

后端 未结 7 1040
挽巷
挽巷 2020-11-22 14:04

I’m making requests to my server using jQuery.post() and my server is returning JSON objects (like { \"var\": \"value\", ... }). However, if any of

7条回答
  •  萌比男神i
    2020-11-22 14:36

    I was trying to save a JSON object from a XHR request into a HTML5 data-* attribute. I tried many of above solutions with no success.

    What I finally end up doing was replacing the single quote ' with it code ' using a regex after the stringify() method call the following way:

    var productToString = JSON.stringify(productObject);
    var quoteReplaced = productToString.replace(/'/g, "'");
    var anchor = '' + productObject.name + '';
    // Here you can use the "anchor" variable to update your DOM element.
    

提交回复
热议问题