Reputation: 8395
Having this list with two JSON strings
on it:
myJSONStringList = ['{"user": "testuser", "data": {"version": 1, "timestamp": "2018-04-03T09:23:43.388Z"}, "group": "33"}',
'{"user": "otheruser", "data": {"version": 2, "timestamp": "2018-04-03T09:23:43.360Z", }, "group": "44"}']
How can I convert this to a JSON array? This is my desired output:
[{"user": "testuser", "data": {"version": 1, "timestamp": "2018-04-03T09:23:43.388Z"}, "group": "33"},
{"user": "otheruser", "data": {"version": 2, "timestamp": "2018-04-03T09:23:43.360Z", }, "group": "44"}]
I know I can do a dirty solution by just doing myJSONStringList.replace("'", "")
, but is there any pythonic solution to this by using, for example, the json
module?
Thanks in advance
Upvotes: 3
Views: 19290
Reputation: 82805
Use json.dumps
before json.loads
to convert your data to dictionary object This also helps prevent valueError: Expecting property name enclosed in double quotes
.
Ex:
import json
myJSONStringList = ['{"user": "testuser", "data": {"version": 1, "timestamp": "2018-04-03T09:23:43.388Z"}, "group": "33"}',
'{"user": "otheruser", "data": {"version": 2, "timestamp": "2018-04-03T09:23:43.360Z", }, "group": "44"}']
print([json.loads(json.dumps(i)) for i in myJSONStringList])
Output:
[u'{"user": "testuser", "data": {"version": 1, "timestamp": "2018-04-03T09:23:43.388Z"}, "group": "33"}', u'{"user": "otheruser", "data": {"version": 2, "timestamp": "2018-04-03T09:23:43.360Z", }, "group": "44"}']
Upvotes: 2
Reputation: 854
decode JSON strings into dicts and put them in a list, last, convert the list to JSON
json_list = []
json_list.append(json.loads(JSON_STRING))
json.dumps(json_list)
or more pythonic syntax
output_list = json.dumps([json.loads(JSON_STRING) for JSON_STRING in JSON_STRING_LIST])
Upvotes: 5