4
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”中取出?!

4

2 回答 2

10

Python has a built-in JSON parsing library. Adding import json provides basic JSON parsing functionality, which can be used as follows:

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.

More information here: http://docs.python.org/2/library/json.html

于 2013-04-28T15:28:42.593 回答
1

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

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 字符串。

于 2013-04-28T15:46:38.850 回答