使用Python从JSON创建数据结构 [英] Creating a Data Structure from JSON Using Python
问题描述
我是python的新手,我有一个json文件,我正在尝试使用它创建使用python的数据结构.
I'm new to python and I have a json file that I'm trying to use to create a data structure using python.
以下是其中一行内容的示例:
Here is a sample of what one of the lines would look like:
[{'name': 'Nick', 'age': '35', 'city': 'New York'}...]
我将其读入内存,但不确定要使用它来创建表还需要执行哪些其他步骤.
I read it into memory, but am unsure what additional steps I would need to take to use it to create a table.
这是我到目前为止尝试过的:
Here is what I have tried so far:
import json
import csv
from pprint import pprint
with open("/desktop/customer_records.json") as customer_records:
data=json.load(customer_records)
for row in data:
print(row)
理想情况下,我会采用以下格式:
Ideally, I would it in the following format:
Name Age City
Nick 35 New York
任何帮助将不胜感激.预先感谢.
Any help would be appreciated. Thanks in advance.
推荐答案
您的问题并未得到精确指定,但是如果您要生成可插入MySQL的SQL,则可以使用以下小程序将JSON转换为SQL语句:
Your problem is not specified too precisely, but if you want to generate SQL that can be inserted into MySQL, here's a little program that converts JSON to a sequence of SQL statements:
#!/usr/bin/env python
import json
# Load data
with open("zz.json") as f:
data=json.load(f)
# Find all keys
keys = []
for row in data:
for key in row.keys():
if key not in keys:
keys.append(key)
# Print table definition
print """CREATE TABLE MY_TABLE(
{0}
);""".format(",\n ".join(map(lambda key: "{0} VARCHAR".format(key), keys)))
# Now, for all rows, print values
for row in data:
print """INSERT INTO MY_TABLE VALUES({0});""".format(
",".join(map(lambda key: "'{0}'".format(row[key]) if key in row else "NULL", keys)))
对于此JSON文件:
[
{"name": "Nick", "age": "35", "city": "New York"},
{"name": "Joe", "age": "21", "city": "Boston"},
{"name": "Alice", "city": "Washington"},
{"name": "Bob", "age": "49"}
]
它生成
CREATE TABLE MY_TABLE(
city VARCHAR,
age VARCHAR,
name VARCHAR
);
INSERT INTO MY_TABLE VALUES('New York','35','Nick');
INSERT INTO MY_TABLE VALUES('Boston','21','Joe');
INSERT INTO MY_TABLE VALUES('Washington',NULL,'Alice');
INSERT INTO MY_TABLE VALUES(NULL,'49','Bob');
为了将来,请让您的问题更具体:)
And for the future, please make your question WAY more specific :)
这篇关于使用Python从JSON创建数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!