Nishant Singh
Nishant Singh

Reputation: 3209

Unable to store or print json data in exact same format

I am having a json data as :

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

I am able to write a python code to store it , my python looks like:

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=(',', ': '))

the above code runs fine but it prints the things as :

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

I am a little hazzy on json stuff.. what am i missing ??? Any help would be highly appreciated

Upvotes: 0

Views: 38

Answers (1)

Alex Paramonov
Alex Paramonov

Reputation: 2730

You should use dictionaries, not arrays, anyway all you code can be written like this (since ES is just a python object it can be mapped to JSON directly, without any manipulations):

#!/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=(',', ': '))

If you want to add some keys and values to it:

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

Upvotes: 1

Related Questions