Change key name in nested JSON structure

前端 未结 3 1579
名媛妹妹
名媛妹妹 2020-12-10 18:53

I have a JSON data structure as shown below:

{
    \"name\": \"World\",
    \"children\": [
      { \"name\": \"US\",
          \"children\": [
           {          


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 19:33

    I don't know why you have a semicolon at the end of your JSON markup (assuming that's what you've represented in the question), but if that's removed, then you can use a reviver function to make modifications while parsing the data.

    var parsed = JSON.parse(myJSONData, function(k, v) {
        if (k === "name") 
            this.key = v;
        else if (k === "children")
            this.value = v;
        else
            return v;
    });
    

    DEMO: http://jsfiddle.net/BeSad/

提交回复
热议问题