Convert list of lists to json format (first list is header)

Viewed 1457

This is a sample list of list.

[
   [hour,name,year,age],
   [12,'pravin',1997,23],
   [12,'navin',1995,25],
   [12,'prashant',1989,30]
]

How can i convert this to this below json using python. I basically want my first list element as key for other list elements. Basically this :

{
  results:[{
      hour : 12,
      name  : 'pravin',
      year : 1995,
      age   : 30   

      },{
      hour : 12,
      name  : 'navin',
      year : 1995,
      age   : 25   

      },{
      hour : 12,
      name  : 'prashant',
      year : 1989,
      age   : 30   

      }
      ]

}
2 Answers

Another solution without pandas:

from pprint import pprint


data = [
   ['hour','name','year','age'],
   [12,'pravin',1997,23],
   [12,'navin',1995,25],
   [12,'prashant',1989,30]
]

out = {'results':[dict(zip(data[0], row)) for row in data[1:]]}

pprint(out)

Prints:

{'results': [{'age': 23, 'hour': 12, 'name': 'pravin', 'year': 1997},
             {'age': 25, 'hour': 12, 'name': 'navin', 'year': 1995},
             {'age': 30, 'hour': 12, 'name': 'prashant', 'year': 1989}]}

You can convert them to pandas' DataFrame object then convert it to json.

import pandas as pd
df = pd.DataFrame(data=results[1:], columns=results[0])
json_results = df.to_json()

The second line is creating a dataframe object from your list of lists. Notice I skipped the first list (which is the columns headers) and use it only for the columns name. The third line creates a json object. You save it using parsing and dumps.

I recommend you to see the examples in pandas documentation on to_json()

Related