andres viena
andres viena

Reputation: 57

Dynamically build a JSON object with an array inside in Python3?

I have to build a json out of an array and send it through a socket to a java application and open it there. I have somehting like

array = ["a","b","c"]

{
  "events":[
        {"id":array[0], "name":"bla1"},
        {"id":array[1], "name":"bla2"}
   ],
   "name": "bla"
}

I have try to use concatenation to no success. How can I do it?

Upvotes: 0

Views: 321

Answers (1)

Ben
Ben

Reputation: 6348

Try:

o ={
    "events":[{"id": item, "name": "blah%s" %(index + 1)}
              for index, item in enumerate(array)],
   "name": "bla"
}

print(o)
# {'events': [{'id': 'a', 'name': 'blah1'}, {'id': 'b', 'name': 'blah2'}, {'id': 'c', 'name': 'blah3'}], 'name': 'bla'}

Upvotes: 1

Related Questions