I’ve found a number of articles with the same issue, but I’m not sure why those solutions aren’t working for me. I have a multidimensional array that has pairs of project and tag key/value pairs. I define the array in the controller like this:
foreach ($data['toolsProjects'] as $tool) {
foreach ($tool->tags as $tag) {
$tag_filter_list[]=array($tool->uid=>$tag->fldTag);
}
}
When I console.log the array on the page it looks like this:
(6) [{…}, {…}, {…}, {…}, {…}, {…}]
0: {project28: 'deer browse'}
1: {project28: 'regeneration'}
2: {project29: 'recreation'}
3: {project11: 'forest health'}
4: {tool20: 'forest health'}
5: {tool20: 'regeneration'}
When I put it into a hidden input, I use json_encode like this:
<input type="hidden" id="tag_filter_list" value="<?php echo json_encode($tag_filter_list) ?>" />
Then, when I try to use it with JQuery, I am getting an error about the formatting of the JSON.
var tag_filter_list=JSON.parse($('#tag_filter_list').val());
I get the error:
Uncaught SyntaxError: Expected property name or ‘}’ in JSON at position 2 at JSON.parse ()
When I console typeof $(‘#tag_filter_list’) it says string, but I guess it’s not in the correct format? But I thought json_encode would take care of that?
Any help is appreciated! Thanks!
2
Answers
Well friend, I believe that the error in this case is the use of single quotes and double quotes. Try:
leave it like this:
rather than:
Another thing, remember that the input must receive a string, but in your case, an object is being passed, so you need to access the key, as in the first index of this array, like:
Good luck!
json_encode()
outputs something like{"key":"value"}
, and if you put that straight into the html markup, it will render like this:So now if you try to read the value of the input it’s just
{
(the rest of it is no longer part of the value). Thus the first character is valid, but the second character (undefined) is not (minimum valid json is{}
)The work around I use for this is to wrap it in urlencode, so
this will replace the double quotes and other markup breaking characters with their escaped html values
then when you go to parse it client side just make sure you wrap it in
decodeURIComponent