I'm new to Python, I'm still learning the concepts and a question has come up. I have the following piece of JSON file:
{
"Id": 1,
"SubGroup": [
{
"Id": 1234,
"SubGroup": [],
"Name": "Out of Service"
},
{
"Id": 5678,
"SubGroup": [],
"Name": "Some Name"
},
{
"Id": 91011,
"SubGroup": [
{
"Id": 9101101,
"SubGroup": [],
"Name": "Other Name_1"
},
{
"Id": 9101102,
"SubGroup": [],
"Name": "Other Name_2"
}
],
"Name": "Company Subsidiary"
}
],
"Name": "Company Name"
}
I´m using the following python code to try to plot all values (including null values) in a table:
import psycopg2
import json
with open("./subgroups.json") as arq_api:
read_data = json.load(arq_api)
data_groupid = []
def get_data():
list_1 = read_data['SubGroup']
for dic in list_1:
group_id = dic.get('Id')
group_name = dic.get('Name')
for a in dic['SubGroup']:
if dic['SubGroup'] == []:
subgrop_id = None
subgrop_name = None
else:
subgrop_id = a['Id']
subgrop_name = a['Name']
data_groupid.append([
group_id,
group_name,
subgrop_id,
subgrop_name
])
get_data()
conn = psycopg2.connect(
"host=myhost dbname=mydb user=myuser password=mypass")
cur = conn.cursor()
cur.execute('TRUNCATE TABLE subgroups')
def post_gre():
for item in data_groupid:
my_data = tuple(item)
cur.execute(
'INSERT INTO subgroups VALUES (%s,%s,%s,%s)', my_data)
post_gre()
conn.commit()
conn.close()
With this code, I am generating the following table:
Table from python code - without null
But I need the table to be like this image below:
Thank you for any help!
Noneas the value of theNULLcolumn should work.if dic['SubGroup'] == []Comparison in Python is not what you expect it to be here. This answer already covers it.