使用Python解析decodeURIComponent JSON字符串

时间:2016-09-28 05:04:12

标签: javascript jquery python json

我有一个“深层”JSON字符串,我需要在URL中作为GET变量传递。它看起来如下:

{
  "meta": {
    "prune": true,
    "returnFields": ["gf", "gh", "gh", "rt"],
    "orient": "split"
  },
  "indicators": [{
    "type": "beta",
    "computeOn": "gf",
    "parameters": {
      "timeperiod": 5,
      "nbdevup": 2,
      "nbdevdn": 2,
      "matype": 0
    }
  }, {
    "type": "alpha",
    "computeOn": "gf",
    "parameters": {
      "timeperiod": 30
    }
  }]
};

使用jQuery.param进行编码时,结果如下:

var recursiveEncoded = jQuery.param(body);
console.log(recursiveEncoded);
meta%5Bprune%5D=true&meta%5BreturnFields%5D%5B%5D=gf&meta%5BreturnFields%5D%5B%5D=gh&meta%5BreturnFields%5D%5B%5D=gh&meta%5BreturnFields%5D%5B%5D=rt&meta%5Borient%5D=split&indicators%5B0%5D%5Btype%5D=beta&indicators%5B0%5D%5BcomputeOn%5D=gf&indicators%5B0%5D%5Bparameters%5D%5Btimeperiod%5D=5&indicators%5B0%5D%5Bparameters%5D%5Bnbdevup%5D=2&indicators%5B0%5D%5Bparameters%5D%5Bnbdevdn%5D=2&indicators%5B0%5D%5Bparameters%5D%5Bmatype%5D=0&indicators%5B1%5D%5Btype%5D=alpha&indicators%5B1%5D%5BcomputeOn%5D=gf&indicators%5B1%5D%5Bparameters%5D%5Btimeperiod%5D=30

将其解码为以下内容:

var recursiveDecoded = decodeURIComponent( jQuery.param(body) );
console.log(recursiveDecoded);

meta[prune]=true&meta[returnFields][]=gf&meta[returnFields][]=gh&meta[returnFields][]=gh&meta[returnFields][]=rt&meta[orient]=split&indicators[0][type]=beta&indicators[0][computeOn]=gf&indicators[0][parameters][timeperiod]=5&indicators[0][parameters][nbdevup]=2&indicators[0][parameters][nbdevdn]=2&indicators[0][parameters][matype]=0&indicators[1][type]=alpha&indicators[1][computeOn]=gf&indicators[1][parameters][timeperiod]=30

如果仅在服务器上使用序列化字符串结果,则将字符串作为键值对中的键:

"query": {
    "{\"meta\":{\"prune\":true,\"returnFields\":[\"gf\",\"gh\",\"gh\",\"rt\"],\"orient\":\"split\"},\"indicators\":[{\"type\":\"beta\",\"computeOn\":\"gf\",\"parameters\":{\"timeperiod\":5,\"nbdevup\":2,\"nbdevdn\":2,\"matype\":0}},{\"type\":\"alpha\",\"computeOn\":\"gf\",\"parameters\":{\"timeperiod\":30}}]}": ""
  },

我的后端处理是用Python完成的。有哪些模块可以将上述结果转换为类似于原始对象的dict

1 个答案:

答案 0 :(得分:1)

好吧,既然我们在评论中将其删除了,我会在这里为后人发布答案。

在JavaScript端使用JSON.stringify的组合来序列化您的数据结构,并在Python端使用json.loads对其进行反序列化。将序列化结构作为查询字符串参数(在您的示例中为“query”)传递,然后从Python中的该查询字符串参数中读取值。好哇!

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify