Reputation: 2728
I json_encode the following ($output) array:
Array
(
[0] => Array
(
[month] => January 2014
[posts] => 2
)
[1] => Array
(
[month] => December 2013
[posts] => 1
)
[2] => Array
(
[month] => August 2013
[posts] => 1
)
)
<?php $json = json_encode($output); ?>
I then print it to the console to check it:
<script>
var myjson = <?php echo $json; ?>;
console.log(myjson);
</script>
In the console, 'myjson' is formed like thus:
[Object { month="January 2014", posts=2},
Object { month="December 2013", posts=1},
Object { month="August 2013", posts=1}] --------------------------($)
an array of objects. Whereas I need it to be like:
[{
"Month": "Jan 2014",
"Posts": 2,
}, {
"Month": "Dec 2013",
"Posts": 1,
}, {
"Month": "Aug 2013",
"Posts": 1,
}];
a json string. If I can somehow remove the 'Object' syntax and instead of '=', there would be colons, I'm good. Looking around on this site and trying various methods:
<?php
$json = json_encode(array_values($output));
$json = json_encode(array_values($output),true);
$json = json_encode($output,true);
?>
I've read about lot's of people having the same difficulty but all solutions tend to be very specific in nature. So my question would be, given any two-dimensional array how do I json_encode it in order to give me or return a json string in javascript?
If I run ($) through http://jsonlint.com/ it returns:
Parse error on line 1:
[ Object{ url=
-----^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', ']'
Upvotes: 0
Views: 158
Reputation:
Put " around the keys for the array, so for example;
Instead of:
$output[][Month] = "January 2014"
type:
$output[]["Month"] = "January 2014"
$output[]["Posts"] = "2"
Then in the program that is receiving the json object, you can do a loop..
for(var i=0;i<myArray.length;i++){
var thisElement = myArray[i];
myMonth = thisElement["Month"];
myPosts = thisElement["Posts"];
}
Alternatively, if you're using angular (like i was which was how i learned json formatting);
When receiving it;
$scope.MonthInfo = data
//on your html page
<div ng-repeat="monthLoop in MonthInfo"> {{monthLoop.Month}} {{monthLoop.Posts}}</div>
Hope this helps somehow :)
Upvotes: 0
Reputation: 1015
It is, in fact, giving you the proper JSON; however, you're echoing the whole thing without delimiters and so it is parsed. If you want the string literal to appear in your console log as a string simple put the output between delimiters:
<script>
var myjson = '<?php echo $json ?>';
console.log(myjson);
</script>
Upvotes: 1
Reputation: 590
You can use Stringify
<script>
var myjson = JSON.stringify(<?= $json; ?>, null, 2);
console.log(myjson);
</script>
Upvotes: 0
Reputation: 6000
Try parseJSON:
<script>
var myjson = $.parseJSON(<?php echo $json; ?>);
console.log(myjson);
</script>
Upvotes: 0