使用Python解析JSON文件

met*_*rsk 0 python parsing json

所以我试图用Python解析一个JSON文件.每次我运行我的脚本,我得到输出,[]我很困惑为什么.这甚至是在python中解析JSON的正确方法吗?

这是我的代码:

import sys
import simplejson
import difflib

filename = sys.argv[1]

data = []

f = file('output.json', "r")
lines = f.readlines()
for line in lines:
        try:
            loadLines = simplejson.loads(line)

            data.append( loadLines['executionTime'])

        except ValueError:
            pass


print data  
Run Code Online (Sandbox Code Playgroud)

ick*_*fay 7

我最好的猜测是,没有一行是有效的JSON.这将导致ValueError每次都被抛出,并且你将永远不会得到data.append(...)作为例外的一直被抛出.

如果整个文件是这样的JSON数组:

[
    {
        "direction": "left",
        "time": 1
    },
    {
        "direction": "right",
        "time": 2
    }
]
Run Code Online (Sandbox Code Playgroud)

然后你可以简单地使用类似的东西:

with open('output.json', 'r') as f:
    data = json.load(f)
Run Code Online (Sandbox Code Playgroud)

但是,如果它是顶级的一堆JSON项,不包含在JSON对象或数组中,如下所示:

{
    "direction": "left",
    "time": 1
}
{
    "direction": "right",
    "time": 2
}
Run Code Online (Sandbox Code Playgroud)

那么你将不得不采用不同的方法:逐个解码项目.不幸的是,我们无法流式传输数据,因此我们首先必须立即加载所有数据:

with open('output.json', 'r') as f:
    json_data = f.read()
Run Code Online (Sandbox Code Playgroud)

要解析单个项目,我们使用decode_raw.这意味着我们需要做一个JSONDecoder:

decoder = json.JSONDecoder()
Run Code Online (Sandbox Code Playgroud)

然后我们继续,剥离字符串左侧的任何空格,检查以确保我们仍然有项目,并解析项目:

while json_data.strip():  # while there's still non-whitespace...
    # strip off whitespace on the left side of the string
    json_data = json_data.lstrip()
    # and parse an item, setting the new data to be whatever's left
    item, json_data = decoder.parse_raw(json_data)
    # ...and then append that item to our list
    data.append(item)
Run Code Online (Sandbox Code Playgroud)

如果您正在进行大量这样的数据收集,那么将它存储在数据库中可能是值得的.像SQLite这样简单的东西就可以了.数据库将使以更有效的方式更容易地进行汇总统计.(这就是他们设计的目标!)如果您经常这样做而不是经常解析JSON,那么它可能会更快地访问数据.