vikram saraswathi vikram saraswathi - 5 months ago 9
JSON Question

Adding nested structure to flat json

I am new to javascript and json, I have a flat json that I get as response after querying a table and the structure is as follows

{"id":"123","First Name": "Jack", "Last Name":"Jill",
"Mobile phone":"1234567", "Home Phone":"0123456",Address Line1":"xxxx",
"Address Line2":"xxxx", "City":"New York"}


I want to convert this flat json into a nested one using some javascript function and I want to convert it as follows. Please let me know how I can achieve this.

{
"Person":
{"id":"123",
"First Name":"Jack",
"Last Name":"Jill",
"phone":
{
"Home Phone":"0123456",
"Mobile Phone":"1234567"
},
"Address":
{
"Address Line1":"xxxx",
"Address Line2":"xxxx",
"City":"New York"
}
}

Answer

There is no automatic way to do this. What you probably want to do is something around this path:

var flatJSONObject = {"id":"123","First Name": "Jack", "Last Name":"Jill", 
"Mobile phone":"1234567", "Home Phone":"0123456","Address Line1":"xxxx",
 "Address Line2":"xxxx", "City":"New York"};

var newJSONObject = {
    person: {
    id: flatJSONObject.id,
    firstName: flatJSONObject['First Name'],
    lastName: flatJSONObject['Last Name'],
    phone:{
        homePhone: flatJSONObject['Home Phone'],
      mobilePhone: flatJSONObject['Mobile phone']
    },
    address: {
        addressLine1: flatJSONObject['Address Line1'],
        addressLine2: flatJSONObject['Address Line2'],
      city: flatJSONObject.City
    }
  }
} 

console.log(newJSONObject);
Comments