Constructing JSON data structures from non-string key python dictionaries

Chris Rebert clp2 at rebertia.com
Wed Nov 21 14:04:53 EST 2012


On Wed, Nov 21, 2012 at 7:48 AM, MRAB <python at mrabarnett.plus.com> 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/)

Nontrivial templating of JavaScript is generally a bad/inelegant
approach. I would instead suggest generating the JSON separately and
loading it from JavaScript via $.getJSON or similar. Or sticking the
JSON into a hidden part of the webpage and then using JSON.parse().

>> 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.

On Wed, Nov 21, 2012 at 8:04 AM,  <hfolch at gmail.com> wrote:
> Thanks for your reply, but the javascript function expects option names to be unquoted, otherwise it won't work.

As a user of HighCharts (and thus, unfortunately, JavaScript), I can
tell you that that's absolutely incorrect.
In JavaScript, {x : y}, {"x" : y}, and {'x' : y} are all equivalent
(at least when x is a valid JavaScript identifier; consult some
non-w3schools JavaScript docs).
Plus, you say you're using JSON; JSON *explicitly mandates that the
keys be quoted* (see RFC 4627).

You are experiencing Python NameErrors because {"x" : y} and {x : y}
aren't equivalent in Python. Python doesn't limit dicts keys to
strings, so `x` is a variable in the latter snippet; x's value is used
as the key.
You cannot expect to take arbitrary, unmodified JavaScript
code/literals, copy-paste them into Python, and expect them to work.


TL;DR:
# foo.py
from json import dumps

colors = SOME_LIST

data = [dict( # use dict() to avoid tedious quoting
    y=55.11,
    color=colors[0],
    drilldown=dict(
        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],
    )
)]

your_json = dumps(data)
# ...serve the JSON somehow...
================
// bar.js
// Not industrial-strength. Assumes the use of jQuery.
// ...
$.getJSON(SOME_URL, function (data) {
    // use 'data', which will be a JavaScript object by this point
});
// ...


Regards,
Chris



More information about the Python-list mailing list