我有下面的JSON文件,它是我从一个API中得到的。
{"Key-1":"Value-1",
"Key-2":[{"Value-2"::Child_Value-1","Value-3":"Child_Value-2"}]
}
{"Key-21":"Value-21",
"Key-22":[{"Value-22":"Child_Value-21","Value-23":"Child_Value-22"}]
}
{"Key-31":"Value-31",
"Key-32":[{"Value-32":"Child_Value-31","Value-33":"Child_Value-32"}]
}我知道这不符合JSON格式,但我想要实现的是提取每个单独的对象并将它们存储在一个单独的文件中。
例如,file1.json应该包含-
[{"Key-1":"Value-1",
"Key-2":[{"Value-2":"Child_Value-1","Value-3":"Child_Value-2"}]
}]而file2.json应该包含-
[{"Key-21":"Value-21",
"Key-22":[{"Value-22":"Child_Value-21","Value-23":"Child_Value-22"}]
}]我试图通过python和shell脚本来实现这一点,但这不会给我带来任何结果。在python/shell中有没有一个很好的库可以帮助你。我对所使用的语言(python、shell-script)有一定的限制
发布于 2016-07-05 19:41:10
这是一个非常慢的东西,不能处理数据中的错误,但它可能会起作用。它是一个生成器,找到第一个'{',然后是下一个'}',并尝试将其间的位解析为JSON。如果失败,它将查找下一个“}”并再次尝试。它产生成功解析的比特。
import json
def generate_json_dictionaries(s):
opening = s.find('{')
while opening != -1:
possible_closing = opening
while True:
possible_closing = s.find('}', start=possible_closing+1)
if possible_closing == -1: return # Data incomplete
try:
j = json.loads(s[opening:possible_closing+1])
yield j
break
except ValueError:
pass
opening = s.find('{', start=possible_closing+1) # Next start未测试。
发布于 2016-07-05 19:35:23
这正是你的问题所要求的(尽管我怀疑它实际上不是你想要的)
filecount = 0
newfilecontents = ''
with open('junksrc.txt', mode='r', encoding='utf-8') as src:
srclines = src.readlines()
for line in srclines:
if '{"Key' in line:
newfilecontents = '[' + line
if '}]' in line:
newfilecontents = newfilecontents + ' ' + line + ' }]\n'
filecount += 1
filename = 'junkdest' + str(filecount) + '.json'
with open(filename, mode='w', encoding='utf-8') as dest:
dest.write(newfilecontents)发布于 2016-07-05 21:46:11
如果获得jq,则可以将数据预处理为标准库的JSON解析器可以轻松解析的形式:
$ jq -s '.' tmp.json
[
{
"Key-1": "Value-1",
"Key-2": [
{
"Value-2": "Child_Value-1",
"Value-3": "Child_Value-2"
}
]
},
{
"Key-21": "Value-21",
"Key-22": [
{
"Value-22": "Child_Value-21",
"Value-23": "Child_Value-22"
}
]
},
{
"Key-31": "Value-31",
"Key-32": [
{
"Value-32": "Child_Value-31",
"Value-33": "Child_Value-32"
}
]
}
]jq可以识别有效的顶级对象流,就像这里所做的那样。-s选项告诉jq在进一步处理之前将它们全部放入单个顶级数组中。
https://stackoverflow.com/questions/38201922
复制相似问题