解析包含JSON列表的文本文件

2024-03-28 11:35:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个目录,它经常转储一组文本文件,如下所示:

  • 你知道吗文件a.json你知道吗
  • 你知道吗文件b.json你知道吗
  • 你知道吗文件c.json你知道吗

每个文件都包含一个JSON“数组”,如下所示:

[
    {
       "id" : "blah",
       "type" : "thingy",
       "ip" : "10.0.0.1",
       "extended" : {
          "var1" : "blah"
        }
    },
    {
       "id" : "blah2",
       "type" : "thingy",
       "ip" : "10.0.0.2",
       "extended" : {
          "var1" : "blah"
        }
    }
]

我想知道什么是读取这些文件并将每个单独的JSON字符串存储到一个数组中以便进一步处理的最有效的方法。我看过json.load(),但这似乎是在单个JSON字符串中读取的,而不是字符串的“数组”。你知道吗

一个可能的解决方案可能是剥离结束括号并通过regex拆分每个JSON对象?你知道吗

编辑:添加一些示例代码:

    json_array = []
    for filename in sorted(os.listdir(CONFIG.DATA_DIR)):
        m = re.match('^.*\.JSON$', filename)
        if m:
            data = json.load(open(CONFIG.DATA_DIR+filename))
            for item in data:
                json_array.append(item)
    return json_array

Tags: 文件字符串ipidjsonextendedtypeload
1条回答
网友
1楼 · 发布于 2024-03-28 11:35:12

您非法格式化了JSON。你不能有任何多余的逗号,所以我用下面的表达式删除了它们。你知道吗

示例

from json import dumps, loads
from os import listdir
from os.path import isfile, join
from re import sub

'''This function transforms a directory of JSON array files and returns a 
   single-dimensional array of all of the items.
'''
def build_json_array(dir):
  result = []
  for f in listdir(dir):
    if isfile(join(dir, f)):
      with open(join(dir, f)) as json_data:
        json_text = sub(',\s+\]', ']', json_data.read()) # We need to repair the data
        result.extend(loads(json_text))
  return result

if __name__ == '__main__':
  print(dumps(build_json_array(CONFIG.DATA_DIR), indent=4))

Tip: You can run your JSON data through a Linter before loading and manipulating it.

如果JSON格式正确,您可以直接从文件加载数据。你知道吗

from json import load

result.extend(load(json_data))

代码高尔夫

实现了一个利用列表理解的单行程序,并通过平展数组来减少数组。你知道吗

from functools import reduce
from json import dumps, load
from os import listdir
from os.path import isfile, join

def build_json_array(dir):
  return reduce(lambda x,y: x+y,(load(open(join(dir,f))) for f in listdir(dir) if isfile(join(dir,f))))

相关问题 更多 >