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

1 Answer 1

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

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.