2013-04-25 70 views
0

我想從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' 
+0

您嘗試加載爲字典的文檔可能不是JSON或Python文檔,或者它包含密鑰中的非法字符。 – 2013-04-25 10:48:42

回答

3

你想用json.loads()(注意s)文件對象,而不是.read()結果,通:

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

json.load()需要一個打開的文件對象,但你傳遞一個字符串; json.loads()需要一個字符串。