Home > database >  Escape character showing up after reading a json file in python
Escape character showing up after reading a json file in python

Time:01-26

I am trying to read a json file (params.json) which contains "$\Omega$" that I intend to be read in latex. Now when I use an escape character, it shows up after loading the json file. What am I doing wrong?

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]}

CodePudding user response:

I suppose you are doing all right. Actually you have one backslash in your strings:

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

Output:

$\Omega$
8

I think you are confused by the display of strings in a dictionary. You can check this simple example in the console:

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

  •  Tags:  
  • Related