Python 如何从json中提取信息?
我试图从json数据中提取一些信息。在下面的代码中,我首先提取包含所需信息的json数据部分,并将其存储在一个文件中。然后我试图打开这个文件,我得到的错误,我的代码。你能帮我找出哪里错了吗Python 如何从json中提取信息?,python,json,Python,Json,我试图从json数据中提取一些信息。在下面的代码中,我首先提取包含所需信息的json数据部分,并将其存储在一个文件中。然后我试图打开这个文件,我得到的错误,我的代码。你能帮我找出哪里错了吗 import json import re input_file = 'path' text = open(input_file).read() experience = re.findall(r'Experience":{"positionsMpr":{"showSection":true," (.+?
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'
回溯(最近一次呼叫最后一次):
文件“test.py”,第13行,在
data=json.load(输入文本)
文件“/home/evi.nastou/.pythonbrew/pythons/Python-2.7.2/lib/python2.7/json/_init__.py”,第274行,处于加载状态
返回加载(fp.read(),
AttributeError:“str”对象没有属性“read”
您希望使用json.loads()
(注意s
),或传入文件对象,而不是的结果。read()
:
json.load()
接受一个打开的文件对象,但您正在传递一个字符串;json.load()
接受一个字符串。您想使用json.load()
(注意s
),或传入文件对象,而不是.read()
:
json.load()
接受一个打开的文件对象,但您向它传递了一个字符串;json.load()
接受字符串。您尝试加载为字典的文档可能不是JSON或Python文档,或者它的键中包含非法字符。您尝试加载为字典的文档可能不是JSON或Python文档,或者它的键中包含非法字符。
text = open('path/temp')
data = json.load(text)