Как сделать мой JSON отформатированный с помощью Python
У меня есть 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
}
]
4 ответа
Примерно так расколоть корневые элементы
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, затем разделит их запятыми и добавит квадратные скобки в начале и в конце
Ниже приведено общее решение для чтения потока текстов 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
)
Этот скрипт на python3 показывает, как читать поток сущностей JSON в файле и как "черпать" их в массив, используя только следующие два заголовка:
import json
from splitstream import splitfile
infile='json.txt'
# Assuming filename contains a stream of JSON texts,
# this function returns each as a Python string
# that can be read using json.loads(_)
def stream(filename):
with open(filename, 'r') as f:
for s in splitfile(f, format="json"):
yield s
obj = []
for jstr in stream(infile):
obj += [ json.loads(jstr) ]
print( json.dumps( obj ) )
Выход
[{"message": ".replace(commentRegExp, '')", "report_id": 1961272}, {"message": ".replace(currDirRegExp, '')", "report_id": 1961269}, {"message": ".replace(jsSuffixRegExp, '');", "report_id": 1961270}]
Форматированный вывод
$ python3 slurpfile.py | jq .
[
{
"message": ".replace(commentRegExp, '')",
"report_id": 1961272
},
{
"message": ".replace(currDirRegExp, '')",
"report_id": 1961269
},
{
"message": ".replace(jsSuffixRegExp, '');",
"report_id": 1961270
}
]
Далее используется модуль "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) )))