0

我正在从 html 作为 json 对象获取文本输入并尝试处理它。但是当我尝试下面的代码时,我在 encoding 和解码中得到 error/(page not rendering) JSON

@app.route('/', methods=['POST'])
def my_form_post():

    text = request.form['text']
    #getting text-input as text = {'a':'1','b':'2'}

    json_input = json.dumps(text)
    ordered_json = json.loads(text, object_pairs_hook=ordereddict.OrderedDict)
    print ordered_json
    processed_text = htmlConvertor(ordered_json)
    #rep(jso)
    return render_template("my-form.html",processed_text=processed_text)

但是当我想用一个局部JSON变量来做这件事时,jso一切都很好。当我使用 html-input 提供相同的输入时,它给出了一个错误,我什至看不到错误,除了显示Internal Server Error 服务器遇到内部错误,无法完成您的请求。服务器过载或应用程序出错。

 @app.route('/', methods=['POST'])
        def my_form_post():

            jso = '''{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}'''

        json_input = json.dumps(jso)
        ordered_json = json.loads(jso, object_pairs_hook=ordereddict.OrderedDict)
        print ordered_json
        processed_text = htmlConvertor(ordered_json)
        #rep(jso)
        return render_template("my-form.html",processed_text=processed_text)

更新:

现在一切正常,但对于整数,它不起作用。例如:

{"name":"yo","price":"250"}

工作完美,但

{"name":"yo","price":250}

不是。解决方案是什么?任何特定的答案,或者我必须integer在 python 中检查,然后在应用任何JSON相关方法和运行之前将其转换为字符串。

4

1 回答 1

1

不确定这是否是您的问题,但{'a':'1','b':'2'}由于单引号,它不是有效的 JSON 对象:

>>> json.loads("{'a':'1','b':'2'}")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python2.6/json/decoder.py", line 319, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib64/python2.6/json/decoder.py", line 336, in raw_decode
    obj, end = self._scanner.iterscan(s, **kw).next()
  File "/usr/lib64/python2.6/json/scanner.py", line 55, in iterscan
    rval, next_pos = action(m, context)
  File "/usr/lib64/python2.6/json/decoder.py", line 171, in JSONObject
    raise ValueError(errmsg("Expecting property name", s, end))
ValueError: Expecting property name: line 1 column 1 (char 1)

如果改为使用双引号,一切正常:

>>> json.loads("{\"a\":\"1\",\"b\":\"2\"}")
{u'a': u'1', u'b': u'2'}

另请注意,要在出现异常时获取堆栈跟踪而不是代码 500 错误,您必须按如下方式启动烧瓶服务器:

app.run(debug = True)
于 2013-09-17T17:50:54.727 回答