Reputation: 37
Having an array
`Array
(
[0] => Array
(
[operative] => 2
[start] => 01:00:00
[end] => 13:00:00
[color] => 543939
)
[1] => Array
(
[operative] => 3
[start] => 08:00:00
[end] => 09:00:00
[color] => 52e612
)
)
`
need to change this into JSON so I use json_encode(), I get a string [{"operative":"2","start":" 01:00:00","end":" 13:00:00","color":"543939"},{"operative":"3","start":" 08:00:00","end":" 09:00:00","color":"52e612"}]
but when I am using JSON into JavaScript by function $.parseJSON() or JSON.parse(), both are giving me not defined.
ok I have used it like this
options1 = '[{"operative":"2","start":" 01:00:00","end":" 13:00:00","color":"543939"},{"operative":"3","start":" 08:00:00","end":" 09:00:00","color":"52e612"}]'
options1 = $.parseJSON(options1);
alert($.param(options1));
But alert is showing me undefined=&undefined=
Upvotes: 0
Views: 89
Reputation: 76405
It looks like you're echo-ing that json encoded string into your javascript. You can do this, and just leave the quotes out:
var options = <?= json_encode($array); ?>;
JSON is an acronym for JavaScript Object Notation. Echoing it into a JS script results in valid javascript arrays and object literals. No need to parse it at all.
Upvotes: 2
Reputation: 4620
Use parseJSON()
done(function (jsonresponse) {
var obj = $.parseJSON(jsonresponse);
console.log(obj);
};
Upvotes: 0
Reputation: 43810
Until you show your code I am assuming that this is what you did:
var object = $.parseJSON(<?php echo json_encode($array)?>);
and this wont work because parseJSON
expects a string as a parameter.
so the solution will be:
var object = $.parseJSON('<?php echo json_encode($array)?>');
Note that it is surrounded by quotes.
Upvotes: 1
Reputation: 19609
JSON.parse() expects the argument to be a string. Make your JSON data a string by surrounding it with 'single-quotes' (because you've used "double quotes" inside the JSON already)
Upvotes: 0
Reputation: 3119
If you are using $.parseJSON() -function, the parseable data should be string:
var json = '[{"operative":"2","start":" 01:00:00","end":" 13:00:00","color":"543939"},{"operative":"3","start":" 08:00:00","end":" 09:00:00","color":"52e612"}]';
console.log($.parseJSON(json));
Upvotes: 4