📜 ⬆️ ⬇️

Working with PERL JSON

Work with the JSON format in PERL.


JSON format

JSON (JavaScript Object Notation) - text data format. An alternative to the XML format. For example, consider the differences between JSON and XML formats. Suppose a developer needs to store information about students in the “Journal students” application. The listing below shows the implementation of data storage using the XML format.
<student> <name></name> <surname></surname> <faculty></faculty> <group>-51</group> <adress> <city></city> <street></street> <house>2</house> <apartment>14</apartment> </adress> </student> <student> <name></name> <surname></surname> <faculty></faculty> <group>-72</group> <adress> <city></city> <street></street> <house>12</house> <apartment>24</apartment> </adress> </student> 


Such a data structure presented in JSON format will look as follows:
 [ { "name": "", "surname": "", "faculty": "", "group": "-72", "adress": { "city": "", "street": "", "house": "12", "apartment": "24" } }, { "name": "", "surname": "", "faculty": "", "group": "-51", "adress": { "city": "", "street": "", "house": "2", "apartment": "14" } } ] 

Formulation of the problem

You need to write a Perl script for parsing a JSON data structure. This is necessary for operations performed on data from the JSON format structure.
JSON and Perl

To work with the JSON format, the JSON-2.53 library is used:
 use JSON; 

The decodeJSON subroutine presented below is designed to convert a JSON data structure into a Perl language data structure (made up of arrays and hashes of varying degrees of nesting).
 sub decodeJSON { my ($JSONText) = @_; my $hashRef = decode_json($JSONText); return @$hashRef; } 

The encodeJSON routine is designed to convert Perl data structures to JSON data structures.
 sub encodeJSON{ my($arrayRef) = @_; $JSONText= JSON->new->utf8->encode($perl_scalar); return $JSONText; } 

Conclusion

The result is a Perl data structure, for which the following functionality will be written in the future:
• Add items;
• Delete items;
• Edit item data;
• Search for the desired item;

')

Source: https://habr.com/ru/post/205130/


All Articles