Friday, December 27, 2019

Read/Write JSON Files with Node.js

How to read and write JSON files in PHP

n a previous post we explained the characteristics of the JSON format. Using JSON, complex data structures can be saved in a plain text file, readable by a person.
In this post we will show how to save and read a JSON-formatted data file from a PHP script.
We will use as an example a file named “data.json” with the following contents:

PHP 5.4

The PHP script below reads a JSON file, modifies the value of one of the elements in the data structure read, and writes the modified data structure to another file:
In line 4 the file contents are read and assigned as a string to the  $str_data variable.
In line 5 the  ‘json_decode’ method is called. This method parses the string into a PHP data structure. Both the associative arrays (Enclosed in curly braces ‘{‘ and ‘}’ in the input file ), and the ‘standard’ arrays (Enclosed in square brackets ‘[‘ and ‘]’ in the input file) are converted into PHP arrays.
In line 7 we see how one of the values inside the data structure can be accessed, by navigating the array tree.
In line 10 the value is modified, and in the next lines the ‘json_encode’ method is used to convert the data structure back into a JSON-formatted string, which is then written into an output file ‘data_out.json’.
As we can see, the call to ‘json_encode’, specifies the ‘JSON_UNESCAPED_UNICODE’ flag. This flag is available since PHP 5.4, and is relevant if we are working with data that includes strings with characteres outside de ASCII set, normally found in most languages other than english.
Without this flag, json_encode converts any non-ASCII character found into unicode escape sequences. For instance, the string ‘Música’ would be written as “Mu00fasica”. Although this is a valid unicode text (and can be read back by json_decode into a PHP variable), it is not well suited to be read by a person. The flag JSON_UNESCAPED_UNICODE ensures that these characters are converted into their equivalent UTF8-encoded character. In this way, any text editor supporting UTF-8 encoding will display the string as “Música”.

PHP versions prior to 5.4

If the PHP version we are using is earlier than 5.4, we can’t use the JSON_UNESCAPED_UNICODE flag.
For this reason, if working with unicode escape sequences is not an option, we must write our own conversion routine to convert from unicode escape sequences to UTF-8. The new script would be like this:
https://blog-en.openalfa.com/how-to-read-and-write-json-files-in-php