5

Using json.dumps I can convert a dictionary to json format like this:

>>> from json import dumps
>>> dumps({'height': 100, 'title': 'some great title'})
'{"title": "some great title", "height": 100}'

However, I'm looking to turn my dictionary into a javascript literal, like this:

{title: "some great title", height: 100}

(Notice there are no double quotes around title and height.)

Is there a Python library to do this?

mickeybob
  • 447
  • 4
  • 10
  • 1
    How exactly are you planning to transfer the data from Python to JavaScript? – thefourtheye Jan 19 '14 at 17:27
  • thefourtheye: Inside an HTML template I will assign the object literal I create from Python to a JavaScript variable. Maybe there's a way to generate the object literal using JavaScript from the output of json.dumps? – mickeybob Jan 19 '14 at 17:30
  • 2
    You can use `JSON.parse` in the JavaScript template part, to convert this string to a valid JavaScript object literal. – thefourtheye Jan 19 '14 at 17:31
  • Thanks. This should suffice for now, though I'm still curious whether I can generate the object literal directly from Python. – mickeybob Jan 19 '14 at 17:34
  • Or like this: `print("{" + ", ".join("%s: %r" % (k, d[k]) for k in d) + "}")` (but using JSON for the transfer between the two languages is much cleaner) – tobias_k Jan 19 '14 at 17:34
  • This is a valid question with many useful applications – Om Solari Dec 25 '22 at 19:25

2 Answers2

1

If you know all your keys are valid tokens you can use this simple code:

import json

def js_list(encoder, data):
    pairs = []
    for v in data:
        pairs.append(js_val(encoder, v))
    return "[" + ", ".join(pairs) + "]"

def js_dict(encoder, data):
    pairs = []
    for k, v in data.iteritems():
        pairs.append(k + ": " + js_val(encoder, v))
    return "{" + ", ".join(pairs) + "}"

def js_val(encoder, data):
    if isinstance(data, dict):
        val = js_dict(encoder, data)
    elif isinstance(data, list):
        val = js_list(encoder, data)
    else:
        val = encoder.encode(data)
    return val

encoder = json.JSONEncoder(ensure_ascii=False)
js_val(encoder, {'height': 100, 'title': 'some great title'})

The return value of js_val() is in your desired format.

Marcus
  • 287
  • 2
  • 7
0

Dirty hack, but could work: subclass JSONEncoder and override _iterencode_dict method, so that it yields key formatted as you want. In python3.3 it is in line 367 of json.encoder module in line yield _encoder(key). You probably want to copy the whole method and change this line to something like yield key if isinstance(key, str) else _encoder(key).

Again - this is really dirty, unless you have no other option - don't do that. Though, it is doable, what is worth knowing if you really need it.

Filip Malczak
  • 3,124
  • 24
  • 44