Spotify Imam Spotify Imam - 4 months ago 8
Python Question

Make JSON Object in python

I want make JSON Object in python like this :

{
"to":["admin"],
"content":{
"message":"everything",
"command":0,
"date":["tag1",...,"tagn"]
},
"time":"YYYYMMDDhhmmss"
}


This is my code in python :

import json

cont = [{"message":"everything","command":0,"data":["tag1","tag2"]}]
json_content = json.dumps(cont,sort_keys=False,indent=2)
print json_content

data = [{"to":("admin"),"content":json_content, "time":"YYYYMMDDhhmmss"}]
json_obj = json.dumps(data,sort_keys=False, indent =2)

print json_obj


But I get the result like this :

[
{
"content": "[\n {\n \"data\": [\n \"tag1\", \n \"tag2\"\n ], \n \"message\": \"everything\", \n \"command\": 0\n }\n]",
"to": "admin",
"time": "YYYYMMDDhhmmss"
}
]


Could someone please help me? Thankyou

Answer

Nested json content

json_content is a json string representation returned by the first call to json.dumps(), this is why you get a string version of the content in the second call to json.dumps(). You need to call json.dumps() once on the whole python object after you place the original content, cont, directly into data.

import json

cont = [{
    "message": "everything",
    "command": 0,
    "data"   : ["tag1", "tag2"]
}]

data = [{
    "to"      : ("admin"), 
    "content" : cont, 
    "time"    : "YYYYMMDDhhmmss"
}]
json_obj = json.dumps(data,sort_keys=False, indent =2)

print json_obj

[
  {
    "content": [
      {
        "data": [
          "tag1", 
          "tag2"
        ], 
        "message": "everything", 
        "command": 0
      }
    ], 
    "to": "admin", 
    "time": "YYYYMMDDhhmmss"
  }
]
Comments