Constructing JSON data structures from non-string key python dictionaries

MRAB python at mrabarnett.plus.com
Wed Nov 21 11:43:15 EST 2012


On 2012-11-21 16:27, MRAB wrote:> On 2012-11-21 16:04, hfolch at gmail.com 
wrote:
 >> On Wednesday, November 21, 2012 3:48:07 PM UTC, MRAB wrote:
 >>> On 2012-11-21 14:59, saikari78 wrote:
 >>>> Hi,
 >>>>
 >>>> I'm using the json module to  create a JSON string, then
 >>>> inserting  that string into a html template containing a javascript
 >>>> function (from the highcharts library: http://www.highcharts.com/)
 >>>>
 >>>> The json string I'm trying to create is to initialize a data
 >>>> variable in the javascript function, that has the following example
 >>>> format.
 >>>>
 >>>> data = [{ y: 55.11, color: colors[0], drilldown: { name: 'MSIE
 >>>> versions', categories: ['MSIE 6.0', 'MSIE 7.0', 'MSIE 8.0', 'MSIE
 >>>> 9.0'], data: [10.85, 7.35, 33.06, 2.81], color: colors[0] } }]
 >>>>
 >>>> However, I don't know how to do that because dictionary keys in
 >>>> python need to be strings. If I try to do the following, Python,of
 >>>> course, complains that y,color,drilldown, etc are not defined.
 >>>>
 >>>>
 >>>> import json
 >>>>
 >>>> data = [ { y:55.11, color:colors[0], drilldown:{name: 'MSIE
 >>>> versions',categories: ['MSIE 6.0', 'MSIE 7.0', 'MSIE 8.0', 'MSIE
 >>>> 9.0'],data: [10.85, 7.35, 33.06, 2.81],color: colors[0] }} ]
 >>>>
 >>>> data_string = json.dumps(data)
 >>>>
 >>>>
 >>>> Many thanks for any suggestions on how to do this.
 >>>>
 >>> Just quote them:
 >>> data = [ { 'y':55.11, 'color':colors[0], 'drilldown':{'name': 'MSIE
 >>> versions', 'categories': ['MSIE 6.0', 'MSIE 7.0', 'MSIE 8.0', 'MSIE
 >>> 9.0'],'data': [10.85, 7.35, 33.06, 2.81],'color': colors[0] }} ]
 >>>
 >>> Incidentally, dictionary keys in Python don't have to be strings,
 >>> but merely  'hashable', which includes integers, floats and tuples
 >>> amongst others.
 >>
 >> Thanks for your reply, but the javascript function expects option
 >> names to be unquoted, otherwise it won't work.
 >
 > Both Python source code and JSON require the dictionary keys to be
 > quoted, so using the json module to generate JavaScript code isn't
 > going to give you what you want.
 >
 > It shouldn't be too difficult to write a simple function to do it,
 > considering the limited range of types.
 >
Here's such a function:

def dump_javascript(data):
     if isinstance(data, dict):
         items = []

         for key, value in data.items():
             items.append(key + ": " + dump_javascript(value))

         return "{" + ", ".join(items) + "}"
     elif isinstance(data, list):
         items = []

         for value in data:
             items.append(dump_javascript(value))

         return "[" + ", ".join(items) + "]"
     else:
         return json.dumps(data)



More information about the Python-list mailing list