0

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 : <class 'str'>

When i working in shell like this :

>>> import json
>>> h = '{"foo":"bar", "foo2":"bar2"}'
>>> type(h)
<class 'str'>
>>> d=json.loads(h)
>>> d
{'foo2': 'bar2', 'foo': 'bar'}
>>> type(d)
<class 'dict'>
>>> 

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.

6
  • Could you show you config.txt file? Commented Oct 19, 2016 at 2:51
  • "imei": "123456789", "sim_no": "+90 xxx xxx xx xx", "device_type": "standart", "hw_version": "1.01", "sw_version": "1.02" Commented Oct 19, 2016 at 2:56
  • It's exactly like that? With quotes? Commented Oct 19, 2016 at 2:58
  • Yes, all text like this. Commented Oct 19, 2016 at 3:00
  • 1
    Add the missing curly braces before calling json.loads? Commented Oct 19, 2016 at 3:21

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.