python - How to extract information from json? -
i trying extract json data information. on following code, first extract part of json data contains information want , store in file. trying open file , error follows code. can me find wrong?
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'] s in data['positions']]) print positions
error:
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'
you want use json.loads()
(note s
), or pass in file object instead of result of .read()
:
text = open('path/temp') data = json.load(text)
json.load()
takes open file object, passing string; json.loads()
takes string.