I want to convert a JSON file I created to a SQLite database.
My json file is like this (containing traffic data from some crossroads in my city):
{
"2011-12-17 16:00": {
"local": "Av. Protásio Alves; esquina Ramiro Barcelos",
"coord": "-30.036916,-51.208093",
"sentido": "bairro-centro",
"veiculos": "automotores",
"modalidade": "semaforo 50-15",
"regime": "típico",
"pistas": "2+c"
},
"2011-12-19 08:38": {
"local": "R. Fernandes Vieira; esquina Protásio Alves",
"coord": "-30.035535,-51.211079",
"sentido": "único",
"veiculos": "automotores",
"modalidade": "semáforo 30-70",
"regime": "típico",
"pistas": "3"
}
}
And I have created nice database with a one-to-many relation with these lines of Python code:
import sqlite3
db = sqlite3.connect("fluxos.sqlite")
c = db.cursor()
c.execute('''create table medicoes
(timestamp text primary key,
local text,
coord text,
sentido text,
veiculos text,
modalidade text,
pistas text)''')
c.execute('''create table valores
(id integer primary key,
quantidade integer,
tempo integer,
foreign key (id) references medicoes(timestamp))''')
How can I programmatically read the keys from each "block" in the JSON file (in this case, "local", "coord", "sentido", "veiculos", "modalidade", "regime", "pistas" e "medicoes"), create the database with the columns in that same order, and then insert the rows with the proper values?
You have this python code:
which I think should be
since the
%operator expects the string to its left to contain formatting codes.Now all you need to make this work is for
keysto be a tuple (or list) containing the values for the new row of the medicoes table in the correct order. Consider the following python code:When I run this with your sample data, I get:
which would seem to be the tuples you require.
You could add the necessary sqlite code with something like this:
Edit: if you don’t want to hard-code the list of columns, you could do something like this:
When I run this it prints:
You could use it with something like this:
The query this code prints when I try it with your sample data is something like this: