Convert JSON To Array Javascript

前端 未结 2 1381
梦谈多话
梦谈多话 2021-01-12 02:43

I am currently receiving a JSON Object From the Server side of my application, the result is this

{\"tags\":\"[{value: 2,label: \'Dubstep\'},{value: 3,label:         


        
相关标签:
2条回答
  • 2021-01-12 02:55
    initSelection: function (element, callback) {
                        var data = $(element).val();
                        callback($.parseJSON(data));
                    }
    
    0 讨论(0)
  • 2021-01-12 03:06

    Assuming you got your server side response in a javascript object called response you could parse the tags string property using the $.parseJSON function. But first you will need to fix your server side code so that it returns a valid JSON string for the tags property (in JSON property names must be enclosed in quotes):

    // This came from the server
    var response = {"tags":"[{\"value\": 2,\"label\": \"Dubstep\"},{\"value\": 3,\"label\": \"BoysIIMen\"},{\"value\": 4,\"label\":\"Sylenth1\"}]"};
    
    // Now you could parse the tags string property into a corresponding
    // javascript array:
    var tags = $.parseJSON(response.tags);
    
    // and at this stage the tags object will contain the desired array
    // and you could access individual elements from it:
    alert(tags[0].label);
    

    If for some reason you cannot modify your server side script to provide a valid JSON in the tags property you could still use eval instead of $.parseJSON:

    var tags = eval(response.tags);
    

    It's not a recommended approach, normally you should avoid using eval because it will execute arbitrary javascript.

    0 讨论(0)
提交回复
热议问题