我必须将json数组传递给服务器使用post请求:
<form action="../../../submit/" method='post' style="margin-top:-10px" id="submitBox">
<input class="attr" type="text" name="task_url" value= "annotate/{{task_name}}/{{taskid}}/{{frame_idx+1}}" hidden>
<input class="attr" type="text" name="frame_id" value= "{{frame.id}}" hidden>
<input class="attr" type="text" name="boxes_info" value = "" hidden id="boxes_info">
<button class="btn btn-default" id="submit" class="attr_sub">
<span class="glyphicon glyphicon-ok-circle"></span>
Submit
</button>
</form>
以下是我如何创建一个json数组并将其传递给输入值
d3.select('#submit').on('click', function(){
var boxes = [];
var box = {};
d3.selectAll('rect').each(function(){
var rect = d3.select(this)
box['xmin'] = rect.attr('x');
box['ymin'] = rect.attr('y');
box['width'] = rect.attr('width');
box['height'] = rect.attr('height');
box['label'] = rect.attr('class');
boxes.push(JSON.stringify(box));
})
boxes = JSON.stringify(boxes);
d3.select('#boxes_info').attr('value',boxes);
})
在服务器端,我得到表单数据:
bboxes = request.form["boxes_info"]
bboxes = json.loads(bboxes)
print bboxes[0]['xmin'] // error: string indices must be integers
print bboxes[0][0] // return '{'
print bboxes
//[u'{"xmin":"433.9936102236422","ymin":"4.8","width":"404.2108626198083","height":"461.96","label":"person"}', u'{"xmin":"433.9936102236422","ymin":"-18.2","width":"404.2108626198083","height":"20","label":"person"}', u'{"xmin":"490.73482428115017","ymin":"291.84","width":"286.517571884984","height":"197.44","label":"handbag"}', u'{"xmin":"490.73482428115017","ymin":"268.84","width":"286.517571884984","height":"20","label":"handbag"}']
好像我必须再次json.loads('bboxes[0]')
。我想我的代码中出错了。任何人都可以告诉我这样做的正确方法是什么?
答案 0 :(得分:1)
看起来您在客户端上执行了JSON.stringify
两次,这就是您需要在服务器上执行两次json.loads
的原因。
您的代码(简化):
d3.select('#submit').on('click', function(){
d3.selectAll('rect').each(function(){
...
boxes.push(JSON.stringify(box)); // stringify each box
})
boxes = JSON.stringify(boxes); // stringify array with stringified boxes
})
相反,尝试在结果数组上使用stringify
一次:
d3.select('#submit').on('click', function(){
d3.selectAll('rect').each(function(){
...
boxes.push(box); // don't stringify heare
})
boxes = JSON.stringify(boxes); // stringify the array
})