最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Flask中把json字符串转换为字典变量

Flask crifan 7123浏览 0评论

Python中,在json字符串和dict字典变量之间转换,用json

但是最近用了Flask的json,去把dict转换为字符串:

from flask import json
def jsonToStr(jsonDict, indent=2):
    return json.dumps(jsonDict, indent=2, ensure_ascii=False)

现在需要搞清楚:

在Flask中,如何把json字符串转换为对应的dict变量。

How to manage JSON requests using Flask for Python Code Example – Runnable

data = json.loads(jsondata)

json – How do I jsonify a list in Flask? – Stack Overflow

python – How to return json using Flask web framework – Stack Overflow

python – json.dumps vs flask.jsonify – Stack Overflow

flask  json vs python json

python – Flask Display Json in a Neat Way – Stack Overflow

API — Flask Documentation (0.11)

try:
    import simplejson as json
except ImportError:
    import json

不用再去导入python的json了。

直接用Flask中导入的json,同样有各种功能,包括loads:

flask.json.dumps(obj, **kwargs)
Serialize obj to a JSON formatted str by using the application’s configured encoder (json_encoder) if there is an application on the stack.
This function can return unicode strings or ascii-only bytestrings by default which coerce into unicode strings automatically. That behavior by default is controlled by the JSON_AS_ASCII configuration variable and can be overridden by the simplejson ensure_ascii parameter.
flask.json.dump(obj, fp, **kwargs)
Like dumps() but writes into a file object.
flask.json.loads(s, **kwargs)
Unserialize a JSON object from a string s by using the application’s configured decoder (json_decoder) if there is an application on the stack.
flask.json.load(fp, **kwargs)¶
Like loads() but reads from a file object.

【总结】

然后用:

from flask import json
def strToJson(jsonStr):
    jsonDict = json.loads(jsonStr, encoding="utf-8")
    gLog.debug("jsonStr=%s, jsonDict=%s", jsonStr, jsonDict)
    return jsonDict

把传入的json字符串,转换为字典变量:

messageStr={
     "type" : "User",
     "id" : "user-4d51faba-97ff-4adf-b256-40d7c9c68103",
     "event" : "SaveLocation",
     "data" : {
      "longitude": 31.2927,
      "latitude": 120.72,
      "shortStr": "双湖湾花园III期",
      "fullStr": "江苏省苏州市吴中区西华林街双湖湾花园III期"
    }
}, messageDict={u’data’: {u’latitude’: 120.72, u’fullStr’: u’\u6c5f\u82cf\u7701\u82cf\u5dde\u5e02\u5434\u4e2d\u533a\u897f\u534e\u6797\u8857\u53cc\u6e56\u6e7e\u82b1\u56edIII\u671f’, u’longitude’: 31.2927, u’shortStr’: u’\u53cc\u6e56\u6e7e\u82b1\u56edIII\u671f’}, u’type’: u’User’, u’id’: u’user-4d51faba-97ff-4adf-b256-40d7c9c68103′, u’event’: u’SaveLocation’}

注:

此处Flask中的json,内部的逻辑是:

try:
    import simplejson as json
except ImportError:
    import json

转载请注明:在路上 » 【已解决】Flask中把json字符串转换为字典变量

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.230 seconds, using 22.08MB memory