将数据框转换为json文件时遇到问题

时间:2019-04-24 18:36:00

标签: python json pandas

import pandas as pd
import json

csv_file = pd.read_csv("file.csv", sep = ",", header = 0, index_col = False)
print(csv_file.head())

csv_file.to_json("file.json", orient = "records", date_format = "epoch", double_precision = 10, force_ascii = True, date_unit = "ms", default_handler = None)

如何将数据框转换为json文件?它在URL中提供了额外的正斜杠,例如:https:\/\/covers.openlibrary.org\/w\/id\/7984916-M.jpg

1 个答案:

答案 0 :(得分:0)

转义的正斜杠是合法的JSON。规范允许这样做。 JSON接收者在加载JSON数据时将对其正确解码。这可以在python中显示。

import pandas as pd
import json
from pandas.compat import StringIO
print(pd.__version__)

csvdata = StringIO("""index,url
1,https://covers.openlibrary.org/w/id/7984916-M.jpg
""")

csv_df = pd.read_csv(csvdata, sep = ",", header = 0, index_col = False)
print(csv_df.head())

jsondata = StringIO()
csv_df.to_json(jsondata, orient = "records", date_format = "epoch", double_precision = 10, force_ascii = True, date_unit = "ms", default_handler = None)

json_str = jsondata.getvalue()
print(json_str)
a_dict = json.loads(json_str)
print(a_dict)

哪个生产

0.24.2
   index                                                url
0      1  https://covers.openlibrary.org/w/id/7984916-M.jpg
[{"index":1,"url":"https:\/\/covers.openlibrary.org\/w\/id\/7984916-M.jpg"}]
[{'index': 1, 'url': 'https://covers.openlibrary.org/w/id/7984916-M.jpg'}]