How do I display JSON data in HTML using Py-script and Pandas?

76 views Asked by At

I'm working on this small project using JSON for the first time. This is also the first time I got back into programming in a while, so I'm a little rusty. Anyways, I've been trying to get Python to work with Pandas and py-script to display json data in HTML, but the code I've tried so far hasn't worked. I just need some help on other solutions.

My Code:

# install and import these modules, using pyscript json
import pandas as pd
from pyscript import document

# open json file and select div for python output
df = pd.read_json('data.json')
data_output = document.querySelector("#pythonoutput")

# let pandas take the stuff and display it
data_output.innerHTML = df.to_string()

JSON data:

{
    "Name": {
        "01":"DragonForce",
        "02":"Black Sabbath",
        "03":"Smash Into Pieces",
        "04":"Slayer"
    },

    "Most Popular Song": {
        "01":"Through The Fire And Flames",
        "02":"Iron Man or Paranoid or War Pigs",
        "03":"Six Feet Under",
        "04":"Raining Blood"
    },

    "Personal Favorite": {
        "01":"Heartbreak Armageddon",
        "02":"Wheels of Confusion",
        "03":"Come Along and Don't Wake Me Up",
        "04":"Praise of Death"
    }
}

The data prints fine in the console if I do print(df.to_string()), but not in html.

I tried to do "element_innerHTML = df.to_string()", expecting it to put the data in the selected element in a string. Nothing came out.

1

There are 1 answers

0
Laurent B. On BEST ANSWER

Using pandas to_html method, it's printing the hmtl file :

import pandas as pd

# open json file
df = pd.read_json('data.json')

# convert DataFrame to HTML table
html_table = df.to_html(index=False, justify='center')

print(html_table)

Display in console :

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: center;">
      <th>Name</th>
      <th>Most Popular Song</th>
      <th>Personal Favorite</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>DragonForce</td>
      <td>Through The Fire And Flames</td>
      <td>Heartbreak Armageddon</td>
    </tr>
    <tr>
      <td>Black Sabbath</td>
      <td>Iron Man or Paranoid or War Pigs</td>
      <td>Wheels of Confusion</td>
    </tr>
    <tr>
      <td>Smash Into Pieces</td>
      <td>Six Feet Under</td>
      <td>Come Along and Don't Wake Me Up</td>
    </tr>
    <tr>
      <td>Slayer</td>
      <td>Raining Blood</td>
      <td>Praise of Death</td>
    </tr>
  </tbody>
</table>

and in Browser :

enter image description here