【问题标题】:Stringify JSON -> Python Server gets dict with key which is stringified stringStringify JSON -> Python Server 获取带有字符串化字符串的键的 dict
【发布时间】:2013-04-22 06:37:29
【问题描述】:
var jsData = {
    id:         'E1',
    firstname:  'Peter',
    lastname:   'Funny',
    project: { id: 'P1' },
    activities: [
        { id: 'A1' },
        { id: 'A2' }
    ]};

var jsonData = JSON.stringify(jsData);


$('#click').click(function(){

    $.ajax({
        url: "test/",
        type: "POST",
        data: jsData,
        dataType: "json",
        success: function (data){
        console.log(data);
        },
        error:function(){$('#text').html('FATAL_ERROR')}

    })
})

这是 JS 代码,jsData 应该发送到服务器(Python)。 在服务器上我得到类似 {'{id:'E1',firstname:'Peter',lastname:'Funny',project: { id:'P1'},activities: [{ id:'A1'},{ id: 'A2' }]};':''}

有没有一种聪明的方法可以将字符串“inner dict”从“outer dict”中取出?!

【问题讨论】:

  • 我不知道您在服务器端使用的是哪个框架,但您应该能够访问request.body 之类的东西并获取数据。顺便说一句 - 当您使用 dataType 时,您希望从服务器返回类型。您应该使用contentType:"application/json" 通知服务器您请求中的数据类型。

标签: python json string


【解决方案1】:

Python 有一个内置的 JSON 解析库。添加import json提供了基本的JSON解析功能,可以使用如下:

import json
personString = "{'{id:'E1',firstname:'Peter',... " # This would contain your JSON string
person = json.loads( personString ) # This will parse the string into a native Python dictionary, be sure to add some error handling should a parsing error occur

person['firstname'] # Yields 'Peter'
person['activities'] # Yields a list with the activities.

更多信息在这里: http://docs.python.org/2/library/json.html

【讨论】:

  • json.loads 将抛出“期望用双引号括起来的属性名称”,因为由于single quotes,personString 不是有效的 json。
  • 示例中的 JSON 根本不会解析,因为我添加的省略号使其 JSON 无效。这显然是一个示例字符串。
【解决方案2】:

因为你使用了错误的变量!

var jsonData = JSON.stringify(jsData);
..
$.ajax({
      ..,
      contentType: "application/json", //Remember to set this.
      data: jsData,
            ^^^^^^ => Shouldn't you be passing "jsonData" here?

当您传递一个简单的 javascript 字典时,jQuery 以百分位编码格式对键和值进行编码。这就是为什么您将内部 dict 视为字符串的原因。

理想情况下(IMO)你必须做的是传递 JSON 字符串而不是部分百分位数编码的字符串。

请注意,您可能必须更改服务器读取数据的方式。这样就不再有 HTTP/POST 请求参数。只是 HTTP 实体部分中的纯 JSON 字符串。

【讨论】:

  • 对,这是一个错误,我用两个变量测试了它!两者似乎都工作正常。 contentType: "application/json" 导致我在服务器上得到一个空字典
猜你喜欢
  • 2014-07-22
  • 2015-11-13
  • 1970-01-01
  • 2014-01-07
  • 2022-01-04
  • 2022-01-16
  • 1970-01-01
  • 2017-07-06
  • 1970-01-01
相关资源
最近更新 更多