timo / json_fast

a naive imperative json parser in perl6, to evaluate performance against JSON::Tiny
Artistic License 2.0
26 stars 20 forks source link

Need a good, practical user example in the README or in examples #74

Closed tbrowder closed 1 year ago

tbrowder commented 3 years ago

I appreciate and use JSON::Fast when I need easy data storage and retrieval, but I usually have to fiddle with how to incorporate it because I've forgotten how I did it the last time.

For someone who only wants to use JSON for data storage and retrieval, a simple example would be useful. Said example would look something like this:

use JSON::Fast;
my %h;
# add some data to the hash...
# name a file for storage
my $jfil = "/path/to/some-data.json";
# convert the hash to JSON
my $jstr = to-json %h;
# save the JSON string to disk
spurt $jfil, $jstr;

Then, another prog uses that data store:

use JSON::Fast;
my $jfil = "/path/to/some-data.json";
my $jstr = slurp $jfil;
my %h = from-json $jstr;
# use the hash...

Of cousrse having methods to allow those steps to be done at one call would be even more useful.

timo commented 1 year ago

hello Tom, i have just put an example in the readme, it currently looks like this:

    use JSON::Fast;
    my $storage-path = $*SPEC.tmpdir.child("json-fast-example-$*PID.json");
    say "using path $storage-path for example";
    for <recreatable monascidian spectrograph bardiest ayins sufi lavanga Dachia> -> $word {
        say "- loading json file";
        my $current-data = from-json ($storage-path.IO.slurp // "\{}");
        # $current-data now contains a Hash object populated with what was in the file
        # (or an empty hash in the very first step when the file didn't exsit yet)

        say "- adding entry for $word";
        $current-data{$word}{"length"} = $word.chars;
        $current-data{$word}{"first letter"} = $word.substr(0,1);

        say "- saving json file";
        $storage-path.IO.spurt(to-json $current-data);
        # to-json gives us a regular string, so we can plop that
        # into the file with the spurt method

        say "json file is now $storage-path.IO.s() bytes big";
        say "===";
    }
    say "here is the entire contents of the json file:";
    say "====";
    say $storage-path.IO.slurp();
    say "====";
    say "deleting storage file ...";
    $storage-path.IO.unlink;

does this help or do you think a set of fully copyable "starters" for common situations or so would be better?

tbrowder commented 1 year ago

I think both would be good. Maybe start with the simple case. Then one with more detail.

Thank you!

tbrowder commented 1 year ago

Sorry to be so late to the dance. Thanks so much!