Convert JSON To Array Javascript

前端 未结 2 1380
梦谈多话
梦谈多话 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 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.

提交回复
热议问题