Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何读取两个连接的JSON文件?_Python_Json_Python 3.x - Fatal编程技术网

Python 如何读取两个连接的JSON文件?

Python 如何读取两个连接的JSON文件?,python,json,python-3.x,Python,Json,Python 3.x,我有一个包含两个包含JSON字符串的文件: { "hello": 2, "world": 3 }{ "something": 5, "else": 6 } 它们各自都是正确的(它们比这更复杂,但始终是一个接一个的两个JSON指令) 因为我可以预测第一个的格式(接近上面的示例),所以我将使用正则表达式解析文件,并最终将它们分离(我只需要第二个JSON): 虽然此解决方案有效,但我希望确保没有更通用的方法来解决此问题。您可以通过将字符串转换为有效的python对象(如字典列表)来格

我有一个包含两个包含JSON字符串的文件:

{
  "hello": 2,
  "world": 3
}{
  "something": 5,
  "else": 6
}
它们各自都是正确的(它们比这更复杂,但始终是一个接一个的两个JSON指令)

因为我可以预测第一个的格式(接近上面的示例),所以我将使用正则表达式解析文件,并最终将它们分离(我只需要第二个JSON):


虽然此解决方案有效,但我希望确保没有更通用的方法来解决此问题。

您可以通过将字符串转换为有效的python对象(如字典列表)来格式化字符串,然后使用json模块加载它:

In [60]: s = """{
  "hello": 2,
  "world": 3
}{
  "something": 5,
  "else": 6
}"""

In [61]: json.loads("[{}]".format(s.replace('}{', '},{')))
Out[61]: [{'hello': 2, 'world': 3}, {'something': 5, 'else': 6}]
试试这个:

my_str = """{
  "hello": 2,
  "world": 3
}{
  "something": 5,
  "else": 6
}"""

fixed_str = my_str.replace('}{', '},{')

my_json = json.loads("[" + fixed_str + "]")

raw_decode
将解析字符串并返回其对象以及对象序列化结束的索引。只要文档能够合理地放入内存中,您就可以轻咬字符串

>>> text="""{
...   "hello": 2,
...   "world": 3
... }{
...   "something": 5,
...   "else": 6
... }
... 
... """

>>> import json
>>> decoder = json.JSONDecoder()
>>> text = text.lstrip() # decode hates leading whitespace
>>> while text:
...     obj, index = decoder.raw_decode(text)
...     text = text[index:].lstrip()
...     print(obj)
... 
{'world': 3, 'hello': 2}
{'else': 6, 'something': 5}

如果它总是}{,那么只需我的{字符串。替换('}{','},{'),然后json.loads(我的{字符串),因为它现在应该是有效的。@Artagel:这是个好主意,谢谢。想把它变成一个答案吗?当然,我添加了它。
>>> text="""{
...   "hello": 2,
...   "world": 3
... }{
...   "something": 5,
...   "else": 6
... }
... 
... """

>>> import json
>>> decoder = json.JSONDecoder()
>>> text = text.lstrip() # decode hates leading whitespace
>>> while text:
...     obj, index = decoder.raw_decode(text)
...     text = text[index:].lstrip()
...     print(obj)
... 
{'world': 3, 'hello': 2}
{'else': 6, 'something': 5}