JSON无法加载到变量中

时间:2019-03-13 09:23:08

标签: python json

我使用一个名为Scholarly.py的模块

https://pypi.org/project/scholarly/

它工作正常,但是我无法将查询的输出存储到任何变量中

这是一个示例性案例(与网站相同)

publication=scholarly.search_pubs_query('Perception of physical stability and center of mass of 3D objects')

要访问结果,我必须使用 print(next('variable')

print(next(publication))

###output
{'_filled': False,
 'bib': {'abstract': 'Humans can judge from vision alone whether an object is '
                     'physically stable or not. Such judgments allow observers '
                     'to predict the physical behavior of objects, and hence '
                     'to guide their motor actions. We investigated the visual '
                     'estimation of physical stability of 3-D objects (shown '
                     'in stereoscopically viewed rendered scenes) and how it '
                     'relates to visual estimates of their center of mass '
                     '(COM). In Experiment 1, observers viewed an object near '
                     'the edge of a table and adjusted its tilt to the '
                     'perceived critical angle, ie, the tilt angle at which '
                     'the object …',
         'author': 'SA Cholewiak and RW Fleming and M Singh',
         'eprint': 'https://jov.arvojournals.org/article.aspx?articleID=2213254',
         'title': 'Perception of physical stability and center of mass of 3-D '
                  'objects',
         'url': 'https://jov.arvojournals.org/article.aspx?articleID=2213254'},
 'citedby': 15,
 'id_scholarcitedby': '15736880631888070187',
 'source': 'scholar',
 'url_scholarbib': 'https://scholar.googleusercontent.com/scholar.bib?q=info:K8ZpoI6hZNoJ:scholar.google.com/&output=citation&scisig=AAGBfm0AAAAAXIjCFpwk1u0XEARPUufLltWIPwQg4_P_&scisf=4&ct=citation&cd=0&hl=en'}

但是,当涉及到JSON时,它仍然不起作用:

json.load(publication)
Traceback (most recent call last):

  File "<ipython-input-43-a51cc3f613b0>", line 1, in <module>
    json.load(publication)

  File "C:\ProgramData\Anaconda3\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),

AttributeError: 'generator' object has no attribute 'read'

我尝试使用其他方式,例如

[How to make a class JSON serializable

结果是:

  

AttributeError:“生成器”对象没有属性“ dict

不知道该怎么办...

1 个答案:

答案 0 :(得分:0)

您的生成器(即publication)生成dictionary对象。

至少在python中,您可以说dictionaryjson的内存功能,通常json是指文件或string遵循key:value结构。使用字典,您可以通过下面的键直接访问值。

a_dictionary = next(publication)
print(a_dictionary['citedby']) # this will output 15 on that particular data

如果出于某种原因确实要将其转换为json,则可以按照以下步骤进行操作。

json_dump = json.dumps(a_dictionary) # convert dictionary to json string object
loaded_json = json.loads(json_dump)
loaded_json['citedby'] # this will also output 15

希望这会有所帮助。