Sunday 15 August 2010

parsing json file using perl -


I am trying to parse a json file in perl. I want to remove the key "name" and its related value. {"Name": "ABC", "id": "123",}, {"name": "PQR", "id": "456",}, {"name": "XYZ", "id" : "789",}]}

I'm trying with code below:

  # / usr / lib / perl using lib qw (..); LWP :: Simple; Use JSON; My $ filename = '/file.txt'; My $ data; If (open (my $ json_str, $ filename)) {local $ / = undef; My $ json = JSON- & gt; new; $ Data = $ json- & gt; Decode (  

But I can not find any output.

Does anyone tell me wrong?

Your JSN file is invalid.

Lines 5, 10, 15 should not end with a comma because it is the last key / value pair of those hashes.

After you fix this, There is a version of code that gives you the expected results:

  Use # / usr / lib / perl strict; Use warnings; Use Lib qw (..); Use JSON qw (); My $ filename = 'file.txt'; My $ json_text = do {open (my $ json_fh, "& lt ;: encoding (UTF-8)", $ filename) or die ("can not open \ $ filename \": $! \ N "); local $ ($ {Data- & gt; {data}}) for $; - $ json_fh & gt;}; my $ json = JSON- & gt; new; My $ data = $ json- & gt; decode ( $ Json_text); {print $ _- & gt; {name}. "\ N";}   

Some problems:

  • You $ Json_stream < $ data-> {Name} should be applied to all members of the array in the JSON file, not for JSN, so you have to initialize them first

    When debugging, make sure That your JSON is valid. Either comes from CAPN or utility.

    JSON can describe complex data structure, when you parse it in Perl, you also get complex data structure. Or to see the data structure

No comments:

Post a Comment