Jump to content

Why json_decode() returns empty?


Recommended Posts

This is my code on a Page template:

{{$videos = $record->customFieldDisplayByKey('youtube_json');}}
{{$videos = json_decode($videos, true);}}
{{print_r($videos);}}

I have tested the content of the field and it is a valid json format.

But when I decode it to use it as a php array, it is empty. 

Link to comment
Share on other sites

I have checked json_last_error() and number 4 pop out: syntax error.

So I have adopted a different approach to cache the array API data: serialize() and unserialize(). But I had also the same syntax issues, that were solved by base64_encode() and base64_decode().

To save in the database:

{{$videos_serialized = base64_encode(serialize($videos));}}

To use it again:

{{$videos = unserialize(base64_decode($videos));}}

Hope this helps someone using json APIs and caching the results.

Link to comment
Share on other sites

5 hours ago, sobrenome said:

I have checked json_last_error() and number 4 pop out: syntax error.

So I have adopted a different approach to cache the array API data: serialize() and unserialize(). But I had also the same syntax issues, that were solved by base64_encode() and base64_decode().

To save in the database:


{{$videos_serialized = base64_encode(serialize($videos));}}

To use it again:


{{$videos = unserialize(base64_decode($videos));}}

Hope this helps someone using json APIs and caching the results.

You should avoid using serialize, it has inherent security issues especially when using it with user generated content.. See warning - https://www.php.net/manual/en/function.unserialize.php

I don't know how you're generating the 'youtube_json' value, but it would be better/safer to look into why the syntax is invalid and address that instead.

Link to comment
Share on other sites

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...