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-Code,jsData应该发送到服务器(Python)。 在服务器上我得到类似{'{id:'E1',名字:'彼得',姓氏:'搞笑',项目:{id:'P1'},活动:[{id:'A1'},{ id:'A2'}]};':''}
是否有一种聪明的方法可以将字符串'内部字典'从“外部字典”中删除?!
答案 0 :(得分:6)
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.
答案 1 :(得分:0)
因为您使用了错误的变量!
var jsonData = JSON.stringify(jsData);
..
$.ajax({
..,
contentType: "application/json", //Remember to set this.
data: jsData,
^^^^^^ => Shouldn't you be passing "jsonData" here?
当您传递一个简单的javascript字典时,jQuery会以百分位编码格式对密钥和值进行编码。这就是你将内部字典视为字符串的原因。
理想情况下(IMO)需要做的是传递JSON字符串而不是部分百分位编码字符串。
请注意,您可能必须更改服务器读取数据的方式。这样就不再有HTTP / POST请求参数了。只是HTTP实体部分中的普通JSON字符串。