user786 has asked for the wisdom of the Perl Monks concerning the following question:
I have written a perl script to edit the a json file.
I need to check if cp is 10000 and set custcap to 99999 if so. If the cp is not equal to 10000, just exit out of the file without making changes.
The script works as expected. It makes the necessary changes and saves the files.
however after the changes,the order of the parameters in JSON file changes>
I read the json spec, My understanding is json is unordered.
can some one help me out with preserving the order
config file
{ "version": "15320029", "global": { "ap": { "log": "info", "hyd": { "log": "info", "qo": false } }, "cus": [ { **"cp": "10000"**, "ser": "XYZ", "usesr": false, "services": { "acc": { "ips": { "usesr": false } } }, "q": { "policy": "CAP", **"custcap": 3000000** } }, { "cp": "10441", "ser": "abc", "usesr": false, "services": { "acc": { "ips": { "usesr": false } } }, "q": { "policy": "CAP", "custcap": 3000000 } } ] }
#!/usr/bin/perl use strict; use warnings; use JSON; my $json; { open my $fh, "<", "cfg.txt" or die("Can't open file \"/Users/hsivaram/cfg.txt\": $!\n"); local $/; $json = <$fh>; } my $data = decode_json($json); for my $cus (@{ $data->{global}{cus} }) { $cus->{q}{custcap} = 99999 if $cus->{cp} == 10000; } $json = JSON->new->utf8->pretty->encode($data); { open my $fh, ">" ,"cfg.txt" or die("Can't open file \"/Users/hsivaram/cfg.txt\": $!\n"); local $/; print $fh $json; }
After script execution the order of the file changes. is there a way to preserve the order ?
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Preserve the order in JSON
by roboticus (Chancellor) on Jun 16, 2015 at 20:33 UTC | |
Re: Preserve the order in JSON
by Laurent_R (Canon) on Jun 16, 2015 at 21:03 UTC | |
Re: Preserve the order in JSON
by afoken (Canon) on Jun 17, 2015 at 07:17 UTC | |
by tye (Sage) on Dec 28, 2016 at 19:34 UTC | |
Re: Preserve the order in JSON
by GotToBTru (Prior) on Jun 16, 2015 at 20:40 UTC | |
Re: Preserve the order in JSON
by u65 (Chaplain) on Jun 17, 2015 at 11:41 UTC | |
by Anonymous Monk on Dec 28, 2016 at 14:09 UTC | |
Re: Preserve the order in JSON
by Anonymous Monk on Jul 11, 2018 at 10:52 UTC | |
by choroba (Archbishop) on Jul 11, 2018 at 10:57 UTC | |
by Anonymous Monk on Oct 21, 2020 at 03:48 UTC | |
by Anonymous Monk on Oct 21, 2020 at 03:50 UTC | |
by tobyink (Canon) on Oct 21, 2020 at 08:55 UTC | |
by Anonymous Monk on Oct 21, 2020 at 08:44 UTC | |
A reply falls below the community's threshold of quality. You may see it by logging in. |
Back to
Seekers of Perl Wisdom