I have a text file like this :
"imei": "123456789",
"sim_no": "+90 xxx xxx xx xx",
"device_type": "standart",
"hw_version": "1.01",
"sw_version": "1.02"
and i want to convert to dictionary this file. Because i want to take values.
import json
from time import sleep
def buffer(data):
dicto=json.loads(data)
print(type(dicto))
file=open("config.txt", "r").read()
jsondata=json.dumps(file)
buffer(jsondata)
result :
When i working in shell like this :
>>> import json
>>> h = '{"foo":"bar", "foo2":"bar2"}'
>>> type(h)
>>> d=json.loads(h)
>>> d
{'foo2': 'bar2', 'foo': 'bar'}
>>> type(d)
>>>
its working but i can't understand why my code not working. When i convert this file to dictionary i want to hold in a buffer. How can i hold this data inside array? Please excuse me i am new in Python.
解决方案
Seems like you could just add the outer curly braces JSON requires:
with open('config.txt', 'r+') as f:
newdata = '{{ {} }}'.format(f.read())
f.seek(0)
f.write(newdata)
Otherwise, the file is already JSON, so no actual use of the json module is required (unless you want to check if it's already legal before modifying, or verify legality after).