Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

前端给后端传输json数据格式问题

后端同事说前端切图仔你给我传个json回来,我说好的没问题。啪地一下,很快啊,我就把json传过去了(传的是json字符串)。原数据对象如下:

let obj = { 
  member: [
    {id: 1, userid: 8191451, check: true},
    {id: 1, userid: 8200249, check: true},
    {id: 1, userid: 8181572, check: true},
    {id: 1, userid: 8190718, check: true}
  ],
  users: [8191451, 8200249, 8181572, 8190718]
}

使用JSON.stringfy()将obj转换为json字符串,数据如下:
"{"member":[{"id":1,"userid":8191451,"check":true},{"id":1,"userid":8200249,"check":true},{"id":1,"userid":8181572,"check":true},{"id":1,"userid":8190718,"check":true}],"users":[8191451,8200249,8181572,8190718]}"
为了好看,将json字符串写在代码块里

"{"member": [
    {"id":1, "userid":8191451, "check":true},
    {"id":1, "userid":8200249, "check":true},
    {"id":1, "userid":8181572, "check":true},
    {"id":1, "userid":8190718, "check":true}],
  "users": [8191451,8200249,8181572,8190718]
}"

过了一会儿...后端说你这不对啊你怎么给我字符串,你懂不懂json是啥啊!我说懂啊,我传的不就是json字符串么?后端说我不要json字符串,我要json,我要的是这样的...

{"member": [
    {"id":1, "userid":8191451, "check":true},
    {"id":1, "userid":8200249, "check":true},
    {"id":1, "userid":8181572, "check":true},
    {"id":1, "userid":8190718, "check":true}],
  "users": [8191451,8200249,8181572,8190718]
}

所以问题就是,前端给后端传json数据不是传json字符串吗?应该传什么格式? 图2/图3?
ps: 感谢回答


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

1、把JSON.stringfy()这个去掉,一般框架都会自动把输出的object转成json字符串,前端接收后也会自动将json字符串转成object
2、json就是一个字符串, 一种数据格式,你同事其实想要的是object,一般的http请求库都会自动把json转成object
3、JSON.stringfy()需要转的是所有数据,不然前端没法自动转,如:

    JSON.stringfy({
        code: 200,
        data: {members: []}
    })
    
    // 而不是
    {
        code: 200,
        data: JSON.stringfy({
            members: []
        })
    }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...