python字符串转换字典json_Python字符串到带有json的字典(不起作用)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值