1

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

  • You really need to fix the source of the string so that you get a valid JSON or at least `eval`able string – Nick Oct 28 '22 at 11:18

1 Answers1

1

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"])
yem
  • 529
  • 1
  • 6
  • 20
  • I removed that extra {. Now it looks like this `'{NODE: {NODE_NAME:TEST_A,NODE_IDE:TEST_A_NODE},QUEUE: {QUEUE_NAME:TEST_QUEUE,QUEUE_TYPE_CD:1}}' ` .. How do I add quotes for key and values ? Thanks for the help – Senthilkumar Duraisamy Oct 28 '22 at 11:23
  • Any idea how I can convert `'{NODE: {NODE_NAME:TEST_A,NODE_IDE:TEST_A_NODE},QUEUE: {QUEUE_NAME:TEST_QUEUE,QUEUE_TYPE_CD:1}}'` to something like this `'{"NODE": "{'NODE_NAME':'TEST_A', 'NODE_IDE':'TEST_A_NODE'}","QUEUE" :"{'QUEUE_NAME':'TEST_QUEUE', 'QUEUE_TYPE_CD':1}"}'` – Senthilkumar Duraisamy Oct 28 '22 at 11:36
  • 1
    I got it now .. I added below `a = re.sub(r':\s?(?![{\[\s])([^,}]+)', r': "\1"', a);a = re.sub(r'(\w+):', r'"\1":', a) and then did json.loads .. It worked – Senthilkumar Duraisamy Oct 28 '22 at 11:38