Python字符串到带有json的字典(不起作用) [英] Python string to dictionary with json (not working)

查看:221
本文介绍了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"

"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'>

当我在shell中像这样工作时:

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'>
>>> 

它可以工作,但是我不明白为什么我的代码不能工作.当我将此文件转换为字典时,我想保存在缓冲区中.我如何将这些数据保存在数组中?请原谅我是Python的新手.

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.

推荐答案

似乎您只需添加JSON需要的外部花括号即可.

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)

否则,该文件已经是JSON,因此不需要实际使用json模块(除非您要在修改之前检查它是否已经合法,或者在之后验证其合法性).

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

这篇关于Python字符串到带有json的字典(不起作用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆