【发布时间】:2020-08-26 14:52:44
【问题描述】:
我想将 JSON 文件转换成正确的格式。 我有一个 JSON 文件,如下所示:
{
"fruit": "Apple",
"size": "Large",
"color": "Red",
"details":"|seedless:true|,|condition:New|"
},
{
"fruit": "Almond",
"size": "small",
"color": "brown",
"details":"|Type:dry|,|seedless:true|,|condition:New|"
}
您可以看到详细信息中的数据可能会有所不同。
我想改成:
{
"fruit": "Apple",
"size": "Large",
"color": "Red",
"seedless":"true",
"condition":"New",
},
{
"fruit": "Almond",
"size": "small",
"color": "brown",
"Type":"dry",
"seedless":"true",
"condition":"New",
}
我曾尝试在 python 中使用 pandas 作为:
import json
import pandas as pd
import re
df = pd.read_json("data.json",lines=True)
#I tried to change the pattern of data in details column as
re1 = re.compile('r/|(.?):(.?)|/')
re2 = re.compile('r\"(.*?)\":\"(.*?)\"')
df.replace({'details' :re1}, {'details' : re2},inplace = True, regex = True);
但是在详细信息列的所有行中将输出作为“对象”。
【问题讨论】:
-
"details":"|Type:dry,|seedless:true|,|condition:New|"那么,逗号的位置会变化吗?我想不出这条绳子的图案。顺便说一句,您的 Python 代码有一个错字:re2 没有右引号。 -
这是我编辑的错字,谢谢@vahdet
-
如果你想要 json 作为输出,为什么要使用 pandas?你想输出为 json 还是 dataframe?
-
我正在尝试将其转换为 csv 然后 json
-
@KunalChaudhari,如果以下答案之一解决了您的问题,您应该接受它(单击相应答案旁边的复选标记)。这有两件事。它让每个人都知道您的问题已得到您满意的解决,并为帮助您的人提供帮助。 See here 以获得完整的解释。
标签: python json regex pandas design-patterns