你可以使用 python 3 运行 sqlite 。这是在我的 mac 上对我有用的:
首先编译可加载扩展:
curl -O http://sqlite.org/2016/sqlite-src-3140100.zip
unzip sqlite-src-3140100.zip
gcc -g -fPIC -dynamiclib sqlite-src-3140100/ext/misc/json1.c -o json1
然后在脚本中使用它:
import sqlite3
conn = sqlite3.connect('testingjson.db')
#load precompiled json1 extension
conn.enable_load_extension(True)
conn.load_extension("./json1")
# create a cursor
c = conn.cursor()
# make a table
# create table NAME_OF_TABLE (NAME_OF_FIELD TYPE_OF_FIELD);
c.execute('create table testtabledos (testfield JSON);')
# Insert a row of data into a table
c.execute("insert into testtabledos (testfield) values (json('{\"json1\": \"works\"}'));")
# Save (commit) the changes
conn.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()
或在外壳中:
.load json1
CREATE TABLE test_table (id INTEGER, json_field JSON);
# insert data into test table
insert into test_table (id, json_field) values (1, json('{"name":"yvan"}'));
insert into test_table (id, json_field) values (2, json('{"name":"sara"}'));
#select json objects from the json column
select * from test_table where json_extract("json_field", '$.name') is not null;
1|{"name":"yvan"}
2|{"name":"sara"}
我希望这更容易。看起来加载扩展(而不是在创建时将它们构建到 sqlite 中)更有意义。我的最新问题是我似乎无法在 CentOS 6 上编译 json1 扩展。
我在这里写了一个指南:https://github.com/SMAPPNYU/smapphowto/blob/master/howto_get_going_with_sqlite_json1.md https://github.com/SMAPPNYU/smapphowto/blob/master/howto_get_going_with_sqlite_json1.md
编辑:为了我的目的,我最终放弃了 json1 。我现在只使用 pysmap转储到csv https://github.com/SMAPPNYU/pysmap#dump_to_csv通过提取我想要的字段来基于列的 csv,然后转储到sqlite_db https://github.com/SMAPPNYU/pysmap#dump_to_sqlite_db从该 csv 创建一个普通的 sqlite 数据库。看pysmap smapp_collection https://github.com/SMAPPNYU/pysmap#smapp_collection