Convert string(without quotes) to Dict in python to loop through it

Question:

I have a string in Python which looks like this

'{NODE: {NODE_NAME:TEST_A,NODE_IDE:TEST_A_NODE},{QUEUE : {QUEUE_NAME:TEST_QUEUE,QUEUE_TYPE_CD:1}}'

I need to convert it to dict to get Node values and Queue Values

I tried eval, ast_eval and json.loads but nothing seems to work

json.loads error :

>>> a='{NODE: {NODE_NAME:TEST_A,NODE_IDE:TEST_A_NODE},{QUEUE : {QUEUE_NAME:TEST_QUEUE,QUEUE_TYPE_CD:1}}'
>>> json.loads(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib64/python3.6/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
>>>

I tried with double quotes also but still error

>>> a = re.sub(r':s?(?![{[s])([^,}]+)', r': "1"', a)
>>> a = re.sub(r'(w+):', r'"1":', a)
>>> a
'{"NODE": {"NODE_NAME": "TEST_A","NODE_IDE": "TEST_A_NODE"},{"QUEUE":{"QUEUE_NAME": "TEST_QUEUE","QUEUE_TYPE_CD": "1"}}'
>>> json.loads(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib64/python3.6/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 60 (char 59)

ast_eval error:

>>> ast.literal_eval(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.6/ast.py", line 48, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "/usr/lib64/python3.6/ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1
    {"NODE": "{"NODE_NAME": "TEST_A","NODE_IDE": "TEST_A_NODE"}",{"QUEUE":"{"QUEUE_NAME": "TEST_QUEUE","QUEUE_TYPE_CD": "1"}"}
                        ^
SyntaxError: invalid syntax

Answers:

I guess the problem comes because you have a nested dict in the string input.
I suggest to write a function instead.
You can check this question answers on stackoverflow.

Answered By: m_koala_kun

What you wrote isn’t a valid dict. There seems to be an extra curly brace before the second key (Queue).

Once you remove that extra curly brace it should be of the correct dict form.
Each key and value should be in quotations of course (unless it’s a variable that was defined beforehand).
This is where you’re going to have a bit of an issue. You’re going to have nested strings within the string.

Let’s say you have the following string: ‘they’re good’ you’ll notice that the quote in the word they’re essentially ends the string. Python solves this by giving you 3 ways to define string.

Single Quotes, Double Quotes, Triple Quotes.

That way python can differentiate between the different start and end points. This is what I did in the below code.

a = '''{"NODE": "{'NODE_NAME':'TEST_A', 'NODE_IDE':'TEST_A_NODE'}","QUEUE" :"{'QUEUE_NAME':'TEST_QUEUE', 'QUEUE_TYPE_CD':1}"}'''

my_dict = eval(a)

# map string values to map
my_dict = {k: eval(v) for k, v in my_dict.items()}

print("DICT: ", my_dict)

# Print NODE values
print("NODE: ", my_dict["NODE"])

# Print QUEUE values
print("QUEUE: ", my_dict["QUEUE"])
Answered By: yem
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.