簡體   English   中英

如何從json提取信息?

[英]How to extract information from json?

我正在嘗試從json數據中提取一些信息。 在以下代碼上,我首先提取包含我想要的信息的json數據部分,並將其存儲在文件中。 然后,我試圖打開此文件,並且收到遵循我的代碼的錯誤。 你能幫我找到我錯了嗎?

import json
import re

input_file = 'path'
text = open(input_file).read()
experience = re.findall(r'Experience":{"positionsMpr":{"showSection":true,"  (.+?),"visible":true,"find_title":"Find others',text)
output_file = open ('/home/evi.nastou/Documenten/LinkedIn_data/Alewijnse/temp', 'w')
output_file.write('{'+experience[0]+'}')
output_file.close()

text = open('path/temp')
input_text = text.read()
data = json.load(input_text)
positions = json.dumps([s['companyName'] for s in data['positions']])
print positions

錯誤:

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    data = json.load(input_text)
  File "/home/evi.nastou/.pythonbrew/pythons/Python-2.7.2/lib/python2.7/json/__init__.py", line 274, in load
     return loads(fp.read(),
 AttributeError: 'str' object has no attribute 'read'

您想使用json.loads() (注意s ), 或者傳入文件對象而不是.read()的結果:

text = open('path/temp')
data = json.load(text)

json.load()一個打開的文件對象,但是您正在向它傳遞一個字符串; json.loads()需要一個字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM