Reputation: 26321
For testing purposes, I wish to use Ajax to request some JSON from the server. From the Ajax client's perspective, the JSON should look like:
json=[
{"source":"pa","jsonstring": '{"a":1,"b":2,"c":3}'},
{"source":"pa","jsonstring": '{"a":1,"b":2,"c":3}'},
{"source":"pa","jsonstring": '{"a":1,"b":2,"c":3}'}
];
Note that jsonstring
is not JSON, but a string, and $.getJSON()
should not parse it into an object.
My attempt is below, however, I get error Parse error: syntax error, unexpected ',' in /var/www/test/src/classes/Ajax.php on line 13
.
How should this be performed?
$content=file_get_contents('../buffer.json',true); //Line 13
$buffer=$content?json_decode($content):[];
$json=json_encode(['a'=>1,'b'=>2,'c'=>3]);
$buffer[]=[
'source'=>'pa',
'jsonstring'=>'"'.$json.'"'
];
$buffer=json_encode($buffer);
file_put_contents('../buffer.json',$buffer);
header('Content-Type: application/json');
echo($buffer);
buffer.json
output is shown below:
[{"source":"pa","jsonstring":"\"{\"a\":1,\"b\":2,\"c\":3}\""},{"source":"pa","jsonstring":"\"{\"a\":1,\"b\":2,\"c\":3}\""}]
Upvotes: 0
Views: 1450
Reputation: 692
Have you tried removing the extra quotes from 'jsonstring'=>'"'.$json.'"'
? If you json_encode it (which it looks like you do), then it is already a string. I think it should be 'jsonstring' => $json
.
Upvotes: 5