3

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

  • 1
    Possible duplicate of [How to dynamically build a JSON object with Python?](http://stackoverflow.com/questions/23110383/how-to-dynamically-build-a-json-object-with-python) – Abhishek Jul 28 '16 at 04:13

1 Answers1

2

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"
  }
]
tmthydvnprt
  • 10,398
  • 8
  • 52
  • 72