vikram saraswathi vikram saraswathi - 1 year ago 91
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.

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

Answer Source

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: {
    firstName: flatJSONObject['First Name'],
    lastName: flatJSONObject['Last Name'],
        homePhone: flatJSONObject['Home Phone'],
      mobilePhone: flatJSONObject['Mobile phone']
    address: {
        addressLine1: flatJSONObject['Address Line1'],
        addressLine2: flatJSONObject['Address Line2'],
      city: flatJSONObject.City

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download