简体   繁体   English

使用 Python 从 JSON 创建数据结构

[英]Creating a Data Structure from JSON Using 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.我是 python 的新手,我有一个 json 文件,我试图用它来创建使用 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.提前致谢。

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:您的问题没有指定得太精确,但是如果您想生成可以插入 MySQL 的 SQL,这里有一个将 JSON 转换为一系列 SQL 语句的小程序:

#!/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)))

For this JSON file:对于这个 JSON 文件:

[
  {"name": "Nick", "age": "35", "city": "New York"},
  {"name": "Joe", "age": "21", "city": "Boston"},
  {"name": "Alice", "city": "Washington"},
  {"name": "Bob", "age": "49"}
]

It generates它产生

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 :)对于未来,请让您的问题更具体:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM