Convert JSON to Perl hash without perl modules
Post ReplyConvert JSON to Perl hash without perl modulesPosted: Monday, October 8, 2018 [21:44:13] - 1
If you have a simple task of converting JSON to Perl hash in the middle of the program - it could be a simple task of running a simple regex: my $json = '{ "id": "myid_transaction", "object": "balance", "amount": 9.95, "available": 1739212000, "created": 1738932756, "currency": "usd", "description": "sample transaction", "fee": 18, "fee_details": [ { "amount": 18, "application": null, "currency": "usd", "description": "Processing fees", "type": "processing_fee" } ], "net": 7.77, "source": "src_trans", "sourced_transfers": { "object": "list", "data": [ ], "has_more": false, "total_count": 0, "url": "this_url_value" }, "status": "pending", "type": "charge" }'; $json =~ s/^\{+//; $json =~ s/\s+$//; $json =~ s/\012/\n/g; $json =~ s/\000/\n/g; $json =~ s/\: /\:/g; $json =~ s/(\n)( )/$1\t/g; $json =~ s/(SPSP)/\t/g; $json =~ s/\:/\,/g; open(TXT,">/data/base/current.txt"); resulting written hash will be: "id","myid_transaction", "object","balance", "amount",9.95, "available",1739212000, "created",1738932756, "currency","usd", "description","sample transaction", "fee",18, "fee_details",[ { "amount",18, "application",null, "currency","usd", "description","Processing fees", "type","processing_fee" } ], "net",7.77, "source","src_trans", "sourced_transfers" => { "object","list", "data",[ ], "has_more",false, "total_count",0, "url","this_url_value" }, "status","pending", "type","charge" Then, data can be loaded later with simple "require" request: and used as a regular Perl hash: %hash |
Accessing hash keys and valuesPosted: Monday, October 8, 2018 [22:54:10] - 2
Accessing values is a straight-forward process if you know keys beforehand. Otherwise it could be a wild guess. When keys are known here is how to access values: print "Fee Description: $hash{fee_details}[0]{description}\n"; # Fee Description: Processing fees print "Fee Type: $hash{fee_details}[0]{type}\n"; # Fee Type: processing_fee print "Sourced Transfers URL: $hash{sourced_transfers}{url}\n"; # Sourced Transfers URL: this_url_value print "Status: $hash{status}\n"; # Status: pending if keys are unknown - you can manually study the hash structure or white a custom program to retrieve data properly. |