Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Create JSON file in specific format

by choroba (Cardinal)
on Apr 24, 2018 at 15:33 UTC ( [id://1213482]=note: print w/replies, xml ) Need Help??


in reply to Create JSON file in specific format

Just create a Perl structure corresponding to the expected JSON and use the JSON module to encode it to JSON. (Update: your expected structure is missing two commas).
#!/usr/bin/perl use warnings; use strict; use JSON; my $struct = { time => time, id => int rand 65536, }; while (<DATA>) { chomp; my ($key, $value, $format, $version) = split /,/; push @{ $struct->{data} }, { key => $key, value => $value, format => $format, version => $version, }; } my $jsonizer = JSON->new->pretty; print $jsonizer->encode($struct); __DATA__ first,1,1.5.6,5.4 two,2,1.4.6,5.4 five,5,1.5.9,5.1

You might need to use JSON::XS or Cpanel::JSON::XS if speed is important to you.

($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

Replies are listed 'Best First'.
Re^2: Create JSON file in specific format
by ovedpo15 (Pilgrim) on Apr 24, 2018 at 15:54 UTC
    what does data in  $struct->{data} stands for?
    Also Is it possible to use without pretty? I understood Its difficult for the DataBase to read it.
    Thank you for the fast answer
      "data" is the key you used on line 4 of your JSON. In other words, $struct is a hash reference, $struct->{data} is the value corresponding to the "data" key in the referenced hash. It contains an array reference to which the code pushes the subhashes.

      To get the output without ->pretty, just delete ->pretty from the code.

      How is a database involved? What error are you getting? How do you interact with it?

      ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
      what does data in $struct->{data} stands for?

      $struct is a hash reference. data is an autovivified key in the referenced hash. (Update: The  -> arrow operator is needed because  $struct is a reference.) Each new hash reference built from each line of input read from an input file or from the  __DATA__ handle (as in the example code) is push-ed to the value of this key.

      Also Is it possible to use without pretty?

      Did you try it? What happened? (Update: And what does the documentation say?)


      Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1213482]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2024-04-25 10:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found