0

Suppose i have string result in json format as below.

{ "errorcode": 0, "message": "Done", "login": [ { "session_timeout": "1800", "token": "1370907977", "sessionid": "##F7A7E49F7FCFF35D3F821201CBF2F7CB5937E4AC99BF2AF74B508A1C8B3F", "username": "" } ] }

How can get a hash table from this like,

hash[errorcode] = 0;  
hash[message] = Done;

PS: without using any additional modules and using simple string functions.

Birei
  • 35,723
  • 2
  • 77
  • 82
Kranthi
  • 195
  • 3
  • 13
  • 4
    *Please* use a module. This looks depressingly like [another let's-parse-Chomsky-type-2-with-Chomsky-type-3 question](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). (That one's about HTML, but the same principle applies.) – michaelb958--GoFundMonica Jun 11 '13 at 07:18

2 Answers2

10

Use JSON module for parsing json structures to perl

use strict;
use warnings;
use JSON;

my $json_text = q({ "errorcode": 0, "message": "Done", "login": [ { "session_timeout": "1800", "token": "1370907977", "sessionid": "##F7A7E49F7FCFF35D3F821201CBF2F7CB5937E4AC99BF2AF74B508A1C8B3F", "username": "" } ] });
my $href = decode_json($json_text);

print $href->{errorcode}, $href->{message}, "\n";
mpapec
  • 50,217
  • 8
  • 67
  • 127
  • Since my script should run on any linux system, which i don't know whether it contains JSON module or not. Then how to get {name,value} pair hash table. – Kranthi Jun 21 '13 at 06:58
  • 1
    @Kranthi if you're with perl 5.14, there is `JSON:PP`. If not you can take it to your project subfolder `lib/` from http://cpansearch.perl.org/src/MAKAMAKA/JSON-PP-2.27202/lib/ and `use lib qw(lib); use JSON::PP;` – mpapec Jun 21 '13 at 10:52
  • How can i get sessionid now? – Kranthi Jun 24 '13 at 06:29
  • `use use JSON::PP;` instead of `JSON` – mpapec Jun 24 '13 at 06:35
  • Yes, i have used JSON::PP only, but if i use $href->{login}->{sessionid}, it is giving **Pseudo-hashes are deprecated at** error, so how to get that data. ? – Kranthi Jun 24 '13 at 07:05
  • 1
    `$href->{login}[0]{sessionid}` as wanted hash is first element inside array – mpapec Jun 24 '13 at 07:15
  • I've been enjoying your nice regex answers, but on this one it's nice to see a non-regex solution +1 :) – zx81 Jun 06 '14 at 22:01
2

I suppose that the non-module solution would be to cut and paste the relevant code from an existing module.

But that would be a terrible idea. Far better to just install the module.

Dave Cross
  • 68,119
  • 3
  • 51
  • 97