Guest User

Untitled

a guest
Jul 21st, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. create or replace function xml2json (xml) returns text
  2. language plperlu as
  3. $func$
  4.  
  5. use XML::XML2JSON;
  6.  
  7. use strict;
  8.  
  9. my $xml = shift;
  10. my $XML2JSON = XML::XML2JSON->new(pretty => 0); # 1 for readable json
  11.  
  12. # work around horrid XML2JSON bug with elements consisting for <foo>0/foo>
  13. $xml =~ s!<([^>]+)>0</\1>!<$1>9999999999999999</$1>!g;
  14. # work around another horrid bug, which turns a string of all blanks into {}
  15. $xml =~ s!<([^>]+)>(\s*)</\1>!<$1>$2,Mxy;zptlk~</$1>!g;
  16.  
  17. my $json = $XML2JSON->convert($xml);
  18.  
  19. $json =~ s/9999999999999999/0/g;
  20. $json =~ s/,Mxy;zptlk~//g;
  21.  
  22. # flatten the structure
  23.  
  24. # nulls:
  25. $json =~ s/\{[^"]*"\@xsi:nil" ?: ?"true"[^"}]*}(,?)/null$1/gs;
  26. # numbers (not in scientific notation):
  27. # don't dequote a number with a leading zero if it's followed by
  28. # another digit - e.g. a zip code
  29. $json =~ s/{[^"]*"\$t" ?: ?"(-?(0|([1-9]\d*))(\.\d+)?)"[^"}]*}(,?)/$1$5/gs;
  30. # booleans:
  31. $json =~ s/{[^"]*"\$t" ?: ?"(true|false)"[^"}]*}(,?)/$1$2/gs;
  32. # strings:
  33. # arrays and composites are not decomposed, they just come in
  34. # as strings
  35. $json =~ s/{[^"]*"\$t" ?: ?"(([^"]|\\")*)"[^"}]*}(,?)/"$1"$3/gs;
  36.  
  37. #remove wrapper
  38. # single row - make it an array of one
  39. $json =~ s/^.*?"row"\s*:\s*\{/\[\{/;
  40. $json =~ s/\}\s*}\s*}\s*$/\}\]/;
  41. # array of rows
  42. $json =~ s/^.*?"row"\s*:\s*\[/\[/;
  43. $json =~ s/\]\s*}\s*}\s*$/\]/;
  44.  
  45.  
  46. return $json;
  47.  
  48. $func$;
  49.  
  50. create or replace function query_to_json(query text) returns text
  51. language sql as
  52. $func$
  53. select xml2json(query_to_xml($1,true,false,''))
  54. $func$;
Add Comment
Please, Sign In to add comment