在python中读取json文件后显示转义符



我正在尝试读取一个json文件(params.json(,该文件包含"\Omega$";我打算用乳胶阅读。现在,当我使用转义符时,它会在加载json文件后显示出来。我做错了什么?

params.json(a file) = {
"Rs" : [1.709e+01, "$\Omega$", 0.1],
"Qh" : [4.942e-06, "F", 0.1],
"Rad" : [1.579, "$\Omega$", 0.1],
"Wad" : [6.009, "$\Omega\cdot^{0.5}$", 0.1],
"Qad" : [1.229e-05, "$F$", 0.1],
"nad" : [4.36424e-01, "-", 0.1],
"Rint" : [5.962e-01, "$\Omega$", 0.1],
"Wint" : [5.524e+01, "$\Omega\cdot^{0.5}$", 0.1],
"tau" : [3.0607e-01, "s", 0.1],
"alpha" : [4.481e-01, "-", 0.1],
"Rp" : [4.31, "$\Omega$", 0.1]
}
def read_params(file):
import json
with open(file, 'r') as fh:
text = json.load(fh)
return text
text = read_params('params.json')
text

#I get the results below with the escape character showing
# {'Rs': [17.09, '$\Omega$', 0.1],
#  'Qh': [4.942e-06, 'F', 0.1],
#  'Rad': [1.579, '$\Omega$', 0.1],
#  'Wad': [6.009, '$\Omega\cdot^{0.5}$', 0.1],
#  'Qad': [1.229e-05, '$F$', 0.1],
#  'nad': [0.436424, '-', 0.1],
#  'Rint': [0.5962, '$\Omega$', 0.1],
#  'Wint': [55.24, '$\Omega\cdot^{0.5}$', 0.1],
#  'tau': [0.30607, 's', 0.1],
#  'alpha': [0.4481, '-', 0.1],
#  'Rp': [4.31, '$\Omega$', 0.1]}

我想你做得很好。实际上,您的字符串中有一个反斜杠:

def read_params(file):
import json
with open(file, 'r') as fh:
text = json.load(fh)
return text
text = read_params('params.json')
print(text['Rs'][1])
print(len(text['Rs'][1]))

输出:

$Omega$
8

我想你被字典里字符串的显示弄糊涂了。你可以在控制台中查看这个简单的例子:

>>> a = {'a': '\'}
>>> a
{'a': '\'}
>>> a['a']
'\'
>>> len(a['a'])
1 # It means you have one backslash in your string
>>> print(a['a'])

最新更新