Home > Software design >  Pass nested JSON data into Html table format
Pass nested JSON data into Html table format

Time:08-10

I am trying to create an HTML report which contains the field and its value over tabular Html format using python.

data.json

[
    {
      "count": 0,
      "company": "abc",
      "state": {
        "city": {}
      },
      "name": "Techno",
      "age": 17,
      "file": "cubix.so"
    },
    {
        "count": 12,
        "company": "def",
        "state": {
          "city": {}
        },
        "name": "Uni",
        "age": 8,
        "file": "cyp.so"
      }
]

The requirement is to read JSON and fetch the file, name, and age values to pass in the Html report file.

def all_details():
    company=0
    age=0
    with open("data.json") as file:
        data = json.loads(file.read())
        for obj in data:
            print(obj['company'], obj['age'])
            message ="""<tr><th style="border:1px solid black;">File Name</th><th style="border:1px solid black;">Company</th><th style="border:1px solid black;">Age</th>"""
            for name in obj[file]:
                message  = """<tr><td style="border:1px solid black;">"""   name   "</td>"
                message  = """<td style="border:1px solid black;">"""   company   "</td>"
                message  = """<td style="border:1px solid black;">"""   age   "</td>"
                message  = "</tr>"
            message ="</table>"
            f = open('file.html','w')
            f.write(message)
            f.close()

need the expected Output in file.html:

enter image description here

CodePudding user response:

Approach 1: You can convert JSON to pandas data frames and from DF to html

import pandas as pd


df = pd.read_json('data.json')   # convert JSON to dataframe
df = df[["file","company","age"]] # select only required columns

html = df.to_html() # convert DF to html

print(html)

Approach 2 : your method - just corrected few errors

def all_details():
    with open("data.json") as file:
        data = json.loads(file.read())
        message ="<table>"
        message  ="""<tr><th style="border:1px solid black;">File Name</th><th style="border:1px solid black;">Company</th><th style="border:1px solid black;">Age</th>"""
        for obj in data:
            print(obj)
            print(obj['company'], obj['age'])
            
            if "name" in obj:
                message  = """<tr><td style="border:1px solid black;">"""    str(obj['name'])   "</td>"
                message  = """<td style="border:1px solid black;">"""   str(obj['company'])   "</td>"
                message  = """<td style="border:1px solid black;">"""   str( obj['age'])   "</td>"
                message  = "</tr>"
        message ="</table>"
        f = open('file.html','w')
        f.write(message)
        f.close()
  • Related