Wednesday 15 September 2010

perl - Adding new key-value pair in an existing json element -


I am getting a Perl script which is basically generating JSON from an XML. This part is working fine but after some commercial reasoning I need to add a new key-value pair to an existing element in JSON.

I am able to insert a completely new element in JSON, but there is no key-value pair An existing element of input JSON

Here is sample JSON:

Now in the above json I'm trying to add element Based on some business logic, a new key-value pair laptop (person-> home-> laptop) (key-value pair example: "key": "123456789"), then the new JSON looks like this:

What is the approach taken in the Perl code:

  1. Change JSON to a hash map first
  2. Attempting to add new element (this is where the problem comes I can add a completely new element, but can not add a key-value pair inside an existing element)
  3. Convert hash back to JSON.

The Perl code for that: (Ignore any missing use statements, to make the script less complicated to highlight the error)

  #! Use / usr / bin / perl strict; Use warnings FATAL = & gt; QW (all); Use data: Dumper; Use JSON; Get the original back to JSON in aSupup (key value added) (JSON is generated from an XML file, $ json, but for this example, please use the sample JSON as described above) My $ tempHash = decode_json ($ Json); #The new key-value pair should be added to the JOSON (in original code it has been generated from commercial logic but in similar format)% filed = ('key', 123456789); # Enter the file now. Think about putting a file key here @ $$ tempHash-> {'Person'} - & gt; {'Home'} - & gt; {'Laptop'}}, $ \% fileData; My $ newJSON = encoded_son ($ tempHash);  

The above code is not working as I expected. It is actually adding a new element {'person'} -> {'home'} -> {'laptop'}} instead of adding it under an existing element (which is the expected behavior).

Does someone ask me to correct the syntax or any other suggestion is appreciated.

I have explained the question in a very simple way (the original code has become very complex now and many different stuff). Tell me if more information is needed or more information is needed for the problem solving which I did.

instead of your lines

 % fileata = ('key' , 123456789); # Enter the file now. Think about putting a file key here @ $$ tempHash-> {'Person'} - & gt; {'Home'} - & gt; {'Laptop'}}, $ \% fileData;  

Use lines

  my ($ key, $ val) = ('key', 123456789); $ TempHash- & gt; {'Person'} - & gt; {'Home'} - & gt; {'Laptops'} - & gt; {$ Key} = $ val;  

You can also insert a bunch of values ​​in the bunch of keys using the hash slice.

  My% filedata = (Key1 => 123, Key2 => 456); @ {$ TempHash-> {Person} {HOME} {laptop}} {keys% filed} = value% filed;  

Which is a more typical but tedious code version

  my @keys = qw (key1 key2); My @ value = (123, 456); @ {$ TempHash-> {Person} {home} {laptop}} {@ key} = @values;  

No comments:

Post a Comment