没有par的Python JSON密钥

2024-10-02 22:36:55 发布

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

我需要从一个JSON格式的文本中获取主键(设备),其中包含大约70.000(子)键/对象 看起来像这样:

{
   "1":{...........}
   "4":{...........}
   "9":{...........}
}

我需要得到“1”、“4”和“9”。但我现在的做法是用2分钟左右的时间来解析文本

^{pr2}$

因为我是用树莓皮做的!在

有更好的方法吗?在

编辑: 我从运行在服务器上的JSON API接收数据:

http://.../ZWaveAPI/Run/devices #this is an array

编辑3:

最终工作代码:(运行2-5秒!:)

import ijson.backends.python as ijson
import urllib

parser = ijson.parse(urllib.urlopen("http://.../ZWaveAPI/Run/devices"))
list = []
for prefix,event,value in parser:
    if event == "map_key" and len(prefix) == 0:
        list.append(value)
return list

Tags: run文本importeventjsonhttpparser编辑
2条回答

您可以使用面向流的迭代JSON解析器来实现,但需要单独安装。试试^{},它将为遇到的每个JSON结构发出事件:

for prefix, event, value in parser:
    if event == 'map_key':
        print value

你试过只买一个设备吗?对于大多数RESTful web服务,如果您看到这样的URL:

"h ttp://.../ZWaveAPI/Run/devices"

您可以通过以下方式获得单个设备:

"h ttp://.../ZWaveAPI/Run/devices/1"

如果它能工作,它将大大减少您必须下载和解析的数据量。在

相关问题 更多 >