Sunday, March 6, 2022

[FIXED] Parse php json to javascript

Issue

So, I have to parse an php json into javascript.

The code looks like this:

$thumbnails = [];
foreach ($images as $key => $image) 
{
  $thumbnails[$image->time] = [
    'src' => MovieEntity::getImageWithPublicPath(
      $movie->id, $image->filename, 130, 0, false
    ),
    'width' => '165px',
    'height' => '95px'
  ];
}

return json_encode($thumbnails, JSON_UNESCAPED_SLASHES);

and the result is:

{"5":{"src":"google.ro","width":"165px","height":"95px"},"7":

I want to take the src, width and height and insert them as pictures like:

<a href="">
  <img src="src of image" width="" height="">
</a>

What do I need to do? This variable in PHP is called $thumbnails, which returns the JSON I showed above.

<?php echo $thumbnails ?>

LE: My solution is:

<?= '<script>var json='.$thumbnails.'</script>' ?>
console.log(json);

This will return you the json in the console.


Solution

If you're using jQuery: $.parseJSON().

If you're using plain javascript: JSON.parse()

// jQuery snipet
var thumbnails = $.parseJSON('<?php echo $thumbnails; ?>');
console.log(thumbnails.src);
console.log(thumbnails.width);
console.log(thumbnails.height);


Answered By - Dacklf

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.