converting a string like '{100-101:[405-874, 405-863], 100-100:[405-862, 405-865]} to dictionary in python
Question:
I am trying to convert a string type to its equivalent Dictionary form:
sample_str='{100-101:[405-874, 405-863], 100-100:[405-862, 405-865]}'
dict_str=json.loads(sample_str)
Error:
"JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)"
Answers:
sample_str='{"100-101":["405-874", "405-863"], "100-100":["405-862", "405-865"]}'
dict_str=json.loads(sample_str)
You need to add the keys as strings in double quotes.
There are two ways to solve it,
Type 1:
Considering the input format is correct which you have mentioned, then the code is
import yaml
s = '{100-101:[405-874, 405-863], 100-100:[405-862, 405-865]}'
d = yaml.load(s, Loader=yaml.Loader)
d
Type 2: The usual way
Here, the input has to be modified slightly to make it string key: value pair
e.g. test_string = ‘{"100-101":"[405-874, 405-863]", "100-100":"[405-862, 405-865]"}’
Then the code is
import json
test_string = '{"100-101":"[405-874, 405-863]", "100-100":"[405-862, 405-865]"}'
print("The original string : " + str(test_string))
res = json.loads(test_string)
res
I am trying to convert a string type to its equivalent Dictionary form:
sample_str='{100-101:[405-874, 405-863], 100-100:[405-862, 405-865]}'
dict_str=json.loads(sample_str)
Error:
"JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)"
sample_str='{"100-101":["405-874", "405-863"], "100-100":["405-862", "405-865"]}'
dict_str=json.loads(sample_str)
You need to add the keys as strings in double quotes.
There are two ways to solve it,
Type 1:
Considering the input format is correct which you have mentioned, then the code is
import yaml
s = '{100-101:[405-874, 405-863], 100-100:[405-862, 405-865]}'
d = yaml.load(s, Loader=yaml.Loader)
d
Type 2: The usual way
Here, the input has to be modified slightly to make it string key: value pair
e.g. test_string = ‘{"100-101":"[405-874, 405-863]", "100-100":"[405-862, 405-865]"}’
Then the code is
import json
test_string = '{"100-101":"[405-874, 405-863]", "100-100":"[405-862, 405-865]"}'
print("The original string : " + str(test_string))
res = json.loads(test_string)
res