[英]Read a JSON file using pandas
I'm trying to convert a JSON file into a data frame and save it to a CSV file at the end.我正在尝试将 JSON 文件转换为数据框,并在最后将其保存到 CSV 文件中。 Well, I am able to do it using Jupyter or Colab, but when I tried on my local python compiler I get many errors.好吧,我可以使用 Jupyter 或 Colab 来做到这一点,但是当我尝试使用本地 python 编译器时,我遇到了很多错误。
Here is my code that works on Colab这是我在 Colab 上工作的代码
import pandas as pd
import datetime
# reading json file
df = pd.read_json(path_or_buf=CONFIG_PROPERTIES)
# normalizing json file
df_items_normalized = pd.json_normalize(data=df.orders, sep='_', record_path='items', meta=['error', 'file','order_id'])
# define parameters to save in csv
today = datetime.datetime.today().strftime('%Y_%m_%d')
path = "/output/pedidos_weedu_" + today + ".csv"
# saving to csv
df_items_normalized.to_csv(path, index=False)
And here is my code when I tried through Pycharm这是我尝试通过 Pycharm 时的代码
import pandas as pd
import datetime
import json
import os
CWD = os.getcwd()
JSON_CONFIG_FILE_PATH = '%s/%s' % (CWD, '12-11-2021.json')
CONFIG_PROPERTIES = {}
try:
with open(JSON_CONFIG_FILE_PATH) as data_file:
CONFIG_PROPERTIES = json.load(data_file)
except IOError as e:
print(e)
print('IOError: Unable to open config.json.')
exit(1)
print(CONFIG_PROPERTIES)
# reading json file
df = pd.read_json(path_or_buf=CONFIG_PROPERTIES)
# normalizing json file
df_items_normalized = pd.json_normalize(data=df.orders, sep='_', record_path='items', meta=['error', 'file','order_id'])
# define parameters to save in csv
today = datetime.datetime.today().strftime('%Y_%m_%d')
path = "/output/pedidos_weedu_" + today + ".csv"
# saving to csv
df_items_normalized.to_csv(path, index=False)
I have changed your code a little:我稍微更改了您的代码:
import pandas as pd
import datetime
import json
import os
from pandas.io.json import json_normalize as jn
CWD = os.getcwd()
JSON_CONFIG_FILE_PATH = "%s/%s" % (CWD, "12-11-2021.json")
print(JSON_CONFIG_FILE_PATH)
CONFIG_PROPERTIES = {}
try:
with open(JSON_CONFIG_FILE_PATH) as data_file:
CONFIG_PROPERTIES = json.load(data_file)
except IOError as e:
print(e)
print("IOError: Unable to open config.json.")
exit(1)
print(CONFIG_PROPERTIES)
df = pd.read_json(path_or_buf=JSON_CONFIG_FILE_PATH)
df_items_normalized = jn(
data=df.orders, sep="_", record_path="items", meta=["error", "file", "order_id"]
)
# define parameters to save in csv
today = datetime.datetime.today().strftime("%Y_%m_%d")
path = "./" + today + ".csv"
# saving to csv
df_items_normalized.to_csv(path, index=False)
this line from pandas.io.json import json_normalize as jn
from this answer .此行from pandas.io.json import json_normalize as jn
from this answer 。
I really do not understant why this answer got a negative point!我真的不明白为什么这个答案得到了否定点!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.