无法使用ijson访问顶级元素? [英] No access to top level elements with ijson?

查看:56
本文介绍了无法使用ijson访问顶级元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用Python的ijson库解析JSON文件.当查看二级元素或使用解析器时,此方法有效,但我更希望直接查看顶级元素的方便.

I've been trying to parse a JSON file with Python's ijson library. This works when looking at second-level elements or when using a parser, but I'd prefer the convenience of looking at top level elements directly.

JSON的基本格式如下:

The JSON is basically formatted like this:

{"foo":{"a":1,"b":2},"bar":{"c":3,"d":4}}

所以,没什么好看的.我想做的是以一种迭代方式遍历它,从而产生"foo"及其值/"bar"及其每次迭代的值. (所以,就像我要json.loads这件事一样.)我的代码如下-我知道它不会同时产生两者,我只是在测试:

So, nothing fancy. What I'd like to do is iterate through it in a way that yields "foo" and its value / "bar" and its value per iteration. (So just like if I were to json.loads this thing.) My code is the following - I know it's not going to yield both, I was just testing:

f=open('test')
i=ijson.items(f,'item')
for j in i:
    print j

items()函数的语法是我从获得的语法stackoverflow .

但是,奇怪的是,循环确实需要时间,但是实际上并没有输出任何东西. (即使我在其中放置print 'qyx'也不是这样,所以我不知道它在做什么.)如果我修改items()函数以解析foo.item,它确实可以工作,但是我能找到的很少的信息表明它也应该适用于顶层.另外,如果我使用以下命令,它可以工作,但是更加不透明:

However, strangely, the loop does take time, but it doesn't actually output anything. (Not even if I put a print 'qyx' in there, so I don't know what it's doing.) If I modify the items() function to parse foo.item, it does work, but what little info I can find indicates that it should work for the top level as well. Plus if I use the following, it works, but it's much more opaque:

i=ijson.parse(f)
for prefix, event, value in i:
   if not prefix or event == 'map_key' or ( '.' in prefix and event in ('start_map','end_map') ):
       continue
   print prefix, event, value

这将输出

foo start_map None
foo.a number 1
foo.b number 2
foo end_map None
bar start_map None
bar.c number 3
bar.d number 4
bar end_map None

...可以进行处理以生成"foo"{"a":1,"b":2}等,但这要麻烦得多.

... which could be processed to yield "foo" and {"a":1,"b":2} etc, but it's much more of a hassle.

推荐答案

尝试一下:

f = open('test')
json_obj = ijson.items(f,'').next() # '' loads everything as only one object.
for (key, value) in json_obj.items():
    print key + " -> " + str(value)

这篇关于无法使用ijson访问顶级元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆