remove double quotes from Json return data using Jquery

前端 未结 8 2116
半阙折子戏
半阙折子戏 2020-12-08 06:29

I use JQuery to get Json data, but the data it display has double quotes. It there a function to remove it?

$(\'div#ListingData\').text(JSON.stringify(data.         


        
8条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 07:23

    I also had this question, but in my case I didn't want to use a regex, because my JSON value may contain quotation marks. Hopefully my answer will help others in the future.

    I solved this issue by using a standard string slice to remove the first and last characters. This works for me, because I used JSON.stringify() on the textarea that produced it and as a result, I know that I'm always going to have the "s at each end of the string.

    In this generalized example, response is the JSON object my AJAX returns, and key is the name of my JSON key.

    response.key.slice(1, response.key.length-1)
    

    I used it like this with a regex replace to preserve the line breaks and write the content of that key to a paragraph block in my HTML:

    $('#description').html(studyData.description.slice(1, studyData.description.length-1).replace(/\\n/g, '
    '));

    In this case, $('#description') is the paragraph tag I'm writing to. studyData is my JSON object, and description is my key with a multi-line value.

提交回复
热议问题