简体   繁体   中英

Hack json.dumps to output unquoted strings?

I acknowledge that Python's json module is for writing json. I'm using the module to generate simple Javascript code too (ie, something that is not valid json). Mostly this works ok, however I need a clean way to pass variable names through dumps . eg a way to write something like:

>>> json.dumps({"varName":F("varReference")})
'{"varName": varReference}'

but I can't figure out how prevent json from adding the quotes. The best I can think of is for F to pad the string with some rare symbol, and then do a regex replace on the output of dumps . Are there any other suggestions? Everything I've seen in json or simplejson require serializable json objects.

One approach could be not to try to do it on the server-side, but always communicate with JSON and then let JavaScript to figure out from this JSON how to build the final object out of it.

  1. Output JavaScript as JSON map "variablename": "variablevalue".

  2. Evaluate variable values on the JavaScript side, by walking through object keys and resolving new value value to each key based on "variableablue" from the global variables.

     Object.getOwnPropertyNames(obj).forEach(function(name, idx, array) { var varName = obj[name]; obj[name] = window[varName]; // Evaluate variable value from global window scope });) 

In example, forEach() is EcmaScript 5, polyfills might be needed for older browsers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM