Im trying to play with a data source for learning purposes. I am trying to take data from public data source and deliver it to a small sqlite DB.
I have this json structure:
[
{
"name": "Aachen",
"id": 1,
"nametype": "Valid",
"recclass": "L5",
"mass (g)": 21,
"fall": "Fell",
"year": "01/01/1880 12:00:00 AM",
"reclat": 50.775,
"reclong": 6.08333,
"GeoLocation": "(50.775, 6.08333)"
},
{
"name": "Aarhus",
"id": 2,
"nametype": "Valid",
"recclass": "H6",
"mass (g)": 720,
"fall": "Fell",
"year": "01/01/1951 12:00:00 AM",
"reclat": 56.18333,
"reclong": 10.23333,
"GeoLocation": "(56.18333, 10.23333)"
},]
so far I managed to work with the below code, but how do I read the data correctly?
this part doesnt work:
name = entry[0];
id = entry[1];
here is part of the code I use:
import json
import sqlite3
conn = sqlite3.connect('rosterdb.sqlite')
cur = conn.cursor()
# Do some setup
cur.executescript('''
DROP TABLE IF EXISTS User;
DROP TABLE IF EXISTS Member;
DROP TABLE IF EXISTS Course;
CREATE TABLE User (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Course (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT UNIQUE
);
CREATE TABLE Member (
user_id INTEGER,
course_id INTEGER,
role INTEGER,
PRIMARY KEY (user_id, course_id)
)
''')
fname = raw_input('Enter file name: ')
if ( len(fname) < 1 ) : fname = 'meteorite.json'
str_data = open(fname).read()
json_data = json.loads(str_data)
for entry in json_data:
name = entry[0];
id = entry[1];
print name, id
When you load json , you get json objects in a list. So you iterate that list using for loop
for item in json_data:
at this point item refers to json object not to list and you are trying to access list in you code by using
name = entry[0];
one more thing dont use (;) in python to end statement and you are using that
You need to get data from dictionary, It should be like this
for item in json_data:
name=item.get('name')
id=item.get('id')
Your code should be like this
import json
import sqlite3
conn = sqlite3.connect('rosterdb.sqlite')
cur = conn.cursor()
# Do some setup
cur.executescript('''
DROP TABLE IF EXISTS User;
DROP TABLE IF EXISTS Member;
DROP TABLE IF EXISTS Course;
CREATE TABLE User (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Course (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT UNIQUE
);
CREATE TABLE Member (
user_id INTEGER,
course_id INTEGER,
role INTEGER,
PRIMARY KEY (user_id, course_id)
)
''')
fname = raw_input('Enter file name: ')
if ( len(fname) < 1 ) : fname = 'meteorite.json'
str_data = open(fname).read()
json_data = json.loads(str_data)
for entry in json_data:
name=entry.get('name')
id=entry.get('id')
print name, id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.