简体   繁体   English

hack json.dumps输出未引用的字符串?

[英]Hack json.dumps to output unquoted strings?

I acknowledge that Python's json module is for writing json. 我承认Python的json模块用于编写json。 I'm using the module to generate simple Javascript code too (ie, something that is not valid json). 我也在使用该模块来生成简单的Javascript代码(即,无效的json)。 Mostly this works ok, however I need a clean way to pass variable names through dumps . 大多数情况下这可以,但是我需要一种干净的方法来通过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. 但我不知道如何防止json添加引号。 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 . 我能想到的最好的是F垫一些罕见的符号的字符串,然后做一个正则表达式上的输出替换dumps Are there any other suggestions? 还有其他建议吗? Everything I've seen in json or simplejson require serializable json objects. 我在jsonsimplejson看到的所有内容都需要可序列化的json对象。

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. 一种方法可能不是尝试在服务器端执行此操作,而是始终与JSON通信,然后让JavaScript从此JSON中找出如何从中构建最终对象。

  1. Output JavaScript as JSON map "variablename": "variablevalue". 将JavaScript输出作为JSON映射“ 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. 通过遍历对象键并根据全局变量中的“ variableablue”将新值值解析为每个键,从而在JavaScript端评估变量值。

     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. 例如, forEach()是EcmaScript 5,较旧的浏览器可能需要polyfills。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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