'Working with string and json in python (json.loads json.dumps) [duplicate]
I have the following string:
results = "{'eventid': '766', 'category': '0', 'uptime': '0', 'severity': '0', 'traptime': '0', 'formatline': '0', 'hostname': '0', 'community': '0', 'agentip': '192.168.250.50', 'eventname': '1.3.6.1.2.1.1.3.0', 'timestamp': '17-12-2015', 'trapoid': '0', 'enterprise': '0'}, {'eventid': '1.3.6.1.4.1.3955.2.7.1', 'category': '0', 'uptime': '0', 'severity': '0', 'traptime': '0', 'formatline': '0', 'hostname': '0', 'community': '0', 'agentip': '192.168.250.50', 'eventname': '1.3.6.1.6.3.1.1.4.1.0', 'timestamp': '17-12-2015', 'trapoid': '0', 'enterprise': '0'}"
And I would like to parse it to JSON. My attempts:
results = json.loads(results)
Gives me a
ValueError: Expecting property name: line 1 column 2 (char 1)
Changing the string to:
results = "'details': {'eventid': '766', 'category': '0', 'uptime': '0', 'severity': '0', 'traptime': '0', 'formatline': '0', 'hostname': '0', 'community': '0', 'agentip': '192.168.250.50', 'eventname': '1.3.6.1.2.1.1.3.0', 'timestamp': '17-12-2015', 'trapoid': '0', 'enterprise': '0'}, {'eventid': '1.3.6.1.4.1.3955.2.7.1', 'category': '0', 'uptime': '0', 'severity': '0', 'traptime': '0', 'formatline': '0', 'hostname': '0', 'community': '0', 'agentip': '192.168.250.50', 'eventname': '1.3.6.1.6.3.1.1.4.1.0', 'timestamp': '17-12-2015', 'trapoid': '0', 'enterprise': '0'}"
Gives me
ValueError: No JSON object could be decoded
Solution 1:[1]
This is not a valid JSON since it has single quotes and not double quotes.
One option would be to safely eval this string with ast.literal_eval():
>>> from ast import literal_eval
>>> results = "{'eventid': '766', 'category': '0', 'uptime': '0', 'severity': '0', 'traptime': '0', 'formatline': '0', 'hostname': '0', 'community': '0', 'agentip': '192.168.250.50', 'eventname': '1.3.6.1.2.1.1.3.0', 'timestamp': '17-12-2015', 'trapoid': '0', 'enterprise': '0'}, {'eventid': '1.3.6.1.4.1.3955.2.7.1', 'category': '0', 'uptime': '0', 'severity': '0', 'traptime': '0', 'formatline': '0', 'hostname': '0', 'community': '0', 'agentip': '192.168.250.50', 'eventname': '1.3.6.1.6.3.1.1.4.1.0', 'timestamp': '17-12-2015', 'trapoid': '0', 'enterprise': '0'}"
>>> literal_eval(results)[0]['eventid']
'766'
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 | alecxe |
