我有一个json,看起来像这样:
{
"message": ".replace(commentRegExp, '')",
"report_id": 1961272
}{
"message": ".replace(currDirRegExp, '')",
"report_id": 1961269
}{
"message": ".replace(jsSuffixRegExp, '');",
"report_id": 1961270
}
如何使用python将其转换为正确的格式我希望json数据看起来像这样:
[
{
"message": ".replace(commentRegExp, '')",
"report_id": 1961272
},
{
"message": ".replace(currDirRegExp, '')",
"report_id": 1961269
},
{
"message": ".replace(jsSuffixRegExp, '');",
"report_id": 1961270
}
]
发布于 2018-07-31 18:53:59
类似下面这样的代码将会分割根元素
import json
import re
json = '{"message":".replace(commentRegExp, '')","report_id":1961272}{"message":".replace(currDirRegExp, '')","report_id":1961269}{"message":".replace(jsSuffixRegExp, '');","report_id":1961270}'
match_array = re.findall("[{].*?[}]", json)
json_new = ""
for x in match_array:
json_new+=(x+",")
json_new = "["+json_new[:-1]+"]"
编辑以从文件中读取;
import json
import re
with open('test.json', 'r') as myfile:
data=re.sub(r"[\n\t\s]*", "", myfile.read())
match_array = re.findall("[{].*?[}]", data)
json_new = ""
for x in match_array:
json_new+=(x+",")
json_new = "["+json_new[:-1]+"]"
print(json_new)
这个解决方案所做的大部分工作都基于[{].*?[}]
正则表达式,它将查找所有的json根元素,然后用逗号分隔它们,并在开头和结尾附加方括号。
发布于 2018-08-01 14:41:25
以下是读取JSON文本流的通用解决方案。它们不需要换行符分隔。但是,假设jq在您的路径上。
为了说明起见,问题中显示的JSON对象也被假定在名为'json.txt‘的文件中。
import json
import sh
infile='json.txt'
cmd = sh.jq('-M', '-s', '.', infile)
obj = json.loads( cmd.stdout )
print( json.dumps(obj, indent=2) )
这将产生所需的输出。
(对于测试,您可以运行:jq -s . infile
)
发布于 2018-08-01 16:22:24
下面使用"pip install jq“模块:https://pypi.org/project/jq/
import json
from jq import jq # jq(CMD).transform(DATA)
infile='json.txt'
def input(filename):
with open(filename, 'r') as f:
return f.read()
str = input( infile );
print( jq(".").transform(text=str, multiple_output=True))
输出
上面的结果是:
[{'message': ".replace(commentRegExp, '')", 'report_id': 1961272}, {'message': ".replace(currDirRegExp, '')", 'report_id': 1961269}, {'message': ".replace(jsSuffixRegExp, '');", 'report_id': 1961270}]
JSON输出
要生成JSON输出:
print(json.loads(json.dumps(jq(".").transform(text=str, multiple_output=True) )))
https://stackoverflow.com/questions/51611500
复制相似问题