3

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

2 Answers 2

5

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])
Sign up to request clarification or add additional context in comments.

Comments

2

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"}']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.