'List within single quotes [duplicate]

I have a list which is in single quotes.

'[{"Name":"name1","value":"value1"},{"name":"name2","value":"value2"}]'

I receive this as an input parameter and I would like to assign this to a variable without the enclosing single quotes in python.

Could you please help?

The sample data received is close to something below..

 '[{"name":"emp_id","value":3232323},{"name":"dd_approval","value":"-paid -fulltime \"05/03/21 19:46\" \"05/04/21 19:46\" [email protected] 3232323"}]'
 json.loads(this string)  

Gives an error as given below

File "/usr/lib64/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib64/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib64/python2.7/json/decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded


Solution 1:[1]

What you have is not a list, but a JSON string representing a list of object, loading it in python will result in a list of dict

import json
a = '[{"Name":"name1","value":"value1"},{"name":"name2","value":"value2"}]'
content = json.loads(a)
print(content) # [{'Name': 'name1', 'value': 'value1'}, {'name': 'name2', 'value': 'value2'}]

Solution 2:[2]

You can use ast.literal_eval

import ast
x = ast.literal_eval('[{"Name":"name1","value":"value1"},{"name":"name2","value":"value2"}]')

If I preform type() on x I will be presented with <class 'list'>

Also everything inside this list turns to its desired form. The code below proves just that.

import ast
x = ast.literal_eval('[{"Name":"name1","value":"value1"},{"name":"name2","value":"value2"}]')
print(x[0])
print(type(x[0]))

output

{'Name': 'name1', 'value': 'value1'}
<class 'dict'>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ann Zen
Solution 2 BuddyBob