1

have a list with values

test = ["mark","will","john"]


using for loop how to convert this into JSON like this

test =[{"name":"mark"},{"name":"john"},{"name":"will"}]

Tried this

for i in test :
    print({"name":i})

1
  • 1
    does your list only contains names or any other values you want to convert it into json Commented Feb 19, 2020 at 9:40

4 Answers 4

5

Create a dictionary within a list comprehension:

test = ["mark","will","john"]
json_list = [{"name": n} for n in test]

same as:

json_list = []
for n in test:
    json_list.append({"name" : n})

then dump to json:

import json
json.dumps(json_list)
Sign up to request clarification or add additional context in comments.

Comments

0
import json

test =[{"name":"mark"},{"name":"john"},{"name":"will"}]

testJson = json.dumps(test)

print(testJson) 

1 Comment

Hi and welcome to stackoverflow, and thank you for answering. While this code might answer the question, can you consider adding some explanation for what the problem was you solved, and how you solved it? This will help future readers to understand your answer better and learn from it.
0

functional way using map()

test = ["mark", "will", "john"]

toJson = lambda _name: {"name": _name} # this expression returns {"name": name} for every iterated "_name"

testJson = map(toJson, test)

for name in testJson:
  print(name)

to print a list of a map object cast it to list, example list(testJson) and you can replace toJson with your lambda expression to customize the result

Comments

0
>>> test = ["mark","will","john"]
>>> final=[]
>>> for i in test:
    d=dict()
    d['name']=i
    final.append(d)
>>> final

>>>[{'name': 'mark'}, {'name': 'will'}, {'name': 'john'}]

1 Comment

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.

Your Answer

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