简体   繁体   中英

Format nested JSON response

I am facing a problem with formatting JSON as response data. I have a class Player, which has the fields name, id, age, top, middle, and bottom. I have another class Position which has fields id, top, middle, and bottom. Player fields top, middle, and bottom come from Position and set it for Player.

My problem is I am getting JSON response data as:

{ id     : 10,
  age    : 16,
  top    : 18,
  middle : 16,
  bottom : 10
}

Whereas I want it as:

 { id  : 10,
   age : 16,
   position : {
     top    : 18,
     middle : 16,
     bottom : 10
   }
 }

You have not told how the JSON object is generated as an output. Here you can crate new JSON object as you wanted by organizing the data from the returned out put like given below:

var returned={
    "id": 10,
    "age": 16,
    "top": 18,
    "middle": 16,
    "bottom": 10
};

var iWanted={
  "id":returned["id"],
  "age":returned["age"],
  "position":{
        "top":returned["top"],
        "middle":returned["middle"],
        "bottom":returned["bottom"]
      }
};

console.log(iWanted);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM