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?

6
  • 1
    How exactly are you planning to transfer the data from Python to JavaScript? Commented Jan 19, 2014 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? Commented Jan 19, 2014 at 17:30
  • 2
    You can use JSON.parse in the JavaScript template part, to convert this string to a valid JavaScript object literal. Commented Jan 19, 2014 at 17:31
  • Thanks. This should suffice for now, though I'm still curious whether I can generate the object literal directly from Python. Commented Jan 19, 2014 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) Commented Jan 19, 2014 at 17:34

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.