remove double quotes from Json return data using Jquery

前端 未结 8 2053
半阙折子戏
半阙折子戏 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:24

    Use replace:

    var test = "\"House\"";
    console.log(test);
    console.log(test.replace(/\"/g, ""));  
    
    // "House"
    // House
    

    Note the g on the end means "global" (replace all).

    0 讨论(0)
  • 2020-12-08 07:24

    I dont think there is a need to replace any quotes, this is a perfectly formed JSON string, you just need to convert JSON string into object.This article perfectly explains the situation : Link

    Example :

    success: function (data) {
    
            // assuming that everything is correct and there is no exception being thrown
            // output string {"d":"{"username":"hi","email":"hi@gmail.com","password":"123"}"}
            // now we need to remove the double quotes (as it will create problem and 
            // if double quotes aren't removed then this JSON string is useless)
            // The output string : {"d":"{"username":"hi","email":"hi@gmail.com","password":"123"}"}
            // The required string : {"d":{username:"hi",email:"hi@gmail.com",password:"123"}"}
            // For security reasons the d is added (indicating the return "data")
            // so actually we need to convert data.d into series of objects
            // Inbuilt function "JSON.Parse" will return streams of objects
            // JSON String : "{"username":"hi","email":"hi@gmail.com","password":"123"}"
            console.log(data);                     // output  : Object {d="{"username":"hi","email":"hi@gmail.com","password":"123"}"}
            console.log(data.d);                   // output : {"username":"hi","email":"hi@gmail.com","password":"123"} (accessing what's stored in "d")
            console.log(data.d[0]);                // output : {  (just accessing the first element of array of "strings")
            var content = JSON.parse(data.d);      // output : Object {username:"hi",email:"hi@gmail.com",password:"123"}" (correct)
            console.log(content.username);         // output : hi 
            var _name = content.username;
            alert(_name);                         // hi
    
    }
    
    0 讨论(0)
提交回复
热议问题