doqvzh345334 2015-11-19 16:14
浏览 75

转换为json数组并通过api传递

I have the following structure:

var arr = [
   {
      aaa: "aaa1",
      bbb: "bbb2"
   },
   {
      ccc: "ccc1"
   }
];

var fooBar = {
   something1: "aaa",
   something2: "bbb",
   someArray: JSON.stringify(arr)
};

I want to convert all of this into one variable as json and pass it to PHP server, like this:

var data = "request=" + JSON.stringify(fooBar);

But when I now try to evaluate this in PHP:

$output = json_decode($_POST['request']);

The output is null.

This is because I'm getting JSON 4 error, which means syntax error.

The problem is that someArray looks like this:

"[{"aaa":"aaa1","bbb":"bbb1"},{"ccc":"ccc1"}]"

Which is not a valid JSON. But how then can I create a valid JSON so that I can read it in PHP later?

  • 写回答

2条回答 默认 最新

  • doupoji3856 2015-11-19 16:23
    关注

    You are calling JSON.stringify twice on some of your data - the result being this:

    ""[{\"aaa\":\"aaa1\",\"bbb\":\"bbb2\"},{\"ccc\":\"ccc1\"}]""
    

    Instead just call it once at the end.

    var arr = [
     {
       aaa: "aaa1",
       bbb: "bbb2"
     },
     {
      ccc: "ccc1"
     }
    ];
    
    var fooBar = {
      something1: "aaa",
      something2: "bbb",
      someArray: arr
    };
    
    var data = "request=" + JSON.stringify(fooBar);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用