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?
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);
When you call:
someArray: JSON.stringify(arr)
You are converting that value to a string instead of an array. What you probably mean to do is
var arr = [
{
aaa: "aaa1",
bbb: "bbb2"
},
{
ccc: "ccc1"
}
];
var fooBar = {
something1: "aaa",
something2: "bbb",
someArray: arr // Assign the array to here
};