首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用python格式化我的json

如何使用python格式化我的json
EN

Stack Overflow用户
提问于 2018-07-31 18:43:41
回答 4查看 109关注 0票数 -1

我有一个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
 }
]
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 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根元素,然后用逗号分隔它们,并在开头和结尾附加方括号。

票数 -1
EN

Stack Overflow用户

发布于 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)

票数 1
EN

Stack Overflow用户

发布于 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) )))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51611500

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档