无法以完全相同的格式存储或打印json数据

时间:2015-11-03 07:31:07

标签: python json elasticsearch

我有一个json数据:

{
"settings" : {
    "number_of_shards" : 1
},
"mappings" : {
    "_default_":{
        "_timestamp" : {
            "enabled" : true,
            "store" : true
        }
    }
  }
}

我能够编写一个python代码来存储它,我的python看起来像:

import json

ES = {}
settings = []
mappings = []
_default_ = []
_timestamp = []
#settings.append({"number_of_shards" : "1"})
#ES["settings"] = settings

m={}
c={}
_timestamp.append({"enabled" : "true", "store" : "true"})
m["_timestamp"]=_timestamp
_default_.append(m)
c["_default_"]=_default_
mappings.append(c)
ES["mappings"] = mappings
settings.append({"number_of_shards" : "1"})
ES["settings"] = settings


print json.dumps(ES,indent=2, separators=(',', ': '))

上面的代码运行正常,但它打印的内容为:

{
  "mappings": [
    {
      "_default_": [
        {
          "_timestamp": [
            {
              "enabled": "true",
              "store": "true"
            }
          ]
        }
      ]
    }
  ],
  "settings": [
    {
      "number_of_shards": "1"
    }
  ]
}

我对json的东西有点模糊..我错过了什么?任何帮助都将受到高度赞赏

1 个答案:

答案 0 :(得分:1)

你应该使用字典,而不是数组,无论如何你所有的代码都可以像这样编写(因为ES只是一个python对象,它可以直接映射到JSON,无需任何操作):

#!/usr/bin/python
import json

ES = {
    "settings": {
        "number_of_shards" : "1"
    },
    "mappings": {
        "_default_": {
            "_timestamp_": {
                "enabled" : "true",
                "store" : "true"
            }
        }
    }
}

print json.dumps(ES,indent=2, separators=(',', ': '))

如果您想为其添加一些键和值:

ES["some_other_key"] = {"some_other_sub_key" : "whatever"}