2016-07-28 4 views
3

でJSONオブジェクトを作成します。これはPythonで私のコードです私はこのようなPythonでJSONオブジェクトを作りたいのpython

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

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 

しかし、私はこのような結果が得られます。

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

誰かお手伝いできますか?ありがとう

+1

の可能性のある重複した[動的Pythonの持つJSONオブジェクトを構築する方法?](http://stackoverflow.com/questions/23110383/how-to-dynamically-build-a- json-object-with-python) – abhishek

答えて

2

ネストされたjsonコンテンツ

json_contentあなたはjson.dumps()への2回目の呼び出しでは、コンテンツの文字列バージョンを取得する理由です、json.dumps()への最初の呼び出しによって返さjson文字列表現です。元のコンテンツcontを直接dataに配置した後は、json.dumps()をpythonオブジェクト全体に1回呼び出す必要があります。

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" 
    } 
] 
+1

私の人生を保存します。ありがとうございます。 –

+0

うれしいです。投票を忘れないでください! ;) – tmthydvnprt

関連する問題