Skip to content

Should you convert XML to JSON? Probably not. If you have to though, try a convention based converter.

License

Notifications You must be signed in to change notification settings

bennyhat/xml_json

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

44 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

XmlJson

hex.pm hex.pm hex.pm github.com

Should you convert XML to JSON? Probably not.

If you have to though (and have decent control over the providers and consumers of the XML and JSON), then there are some decent conventions out there for lossless and near-lossless conversion, such as:

Presently this only supports Parker, BadgerFish and AWS API and is largely happy path testing with the examples provided by each convention. That being said, eventually this will come up to a > 0 major version when that is all worked out.

Otherwise, this does NOT handle massive XML documents with grace, as it converts to a full JSON/Map object in memory.

A port of the great Python library xmljson

Usage

Parker

iex> XmlJson.Parker.deserialize("<root><dog>cat</dog></root>", preserve_root: true)
{:ok, %{"root" => %{"dog" => "cat"}}}

iex> XmlJson.Parker.serialize(%{"root" => %{"dog" => "cat"}}, preserve_root: "root")
{:ok, "<root><dog>cat</dog></root>"}

BadgerFish

iex> XmlJson.BadgerFish.deserialize("<root attr=\"hello\"><dog>cat</dog></root>")
{:ok, %{"root" => %{"@attr" => "hello", "dog" => %{"$" => "cat"}}}}

iex> XmlJson.BadgerFish.serialize(%{"root" => %{"@attr" => "hello", "dog" => %{"$" => "cat"}}})
{:ok, "<root attr=\"hello\"><dog>cat</dog></root>"}

AWS API

Based on common conventions seen in at least the EC2 and ELBv2 XML APIs

iex> XmlJson.AwsApi.deserialize("<root><member><dog>cat</dog></member></root>")
{:ok, %{"root" => [%{"dog" => "cat"}]}}

iex> XmlJson.AwsApi.serialize(%{"root" => [%{"dog" => "cat"}]})
{:ok, "<root><member><dog>cat</dog><member></root>"}

iex> XmlJson.AwsApi.serialize_as_params(%{"root" => [%{"dog" => "cat"}, %{"dog" => "horse"}]})
{:ok, %{"root.member.1.dog" => "cat", "root.member.2.dog" => "horse"}}

Installation

The package can be installed by adding xml_json to your list of dependencies in mix.exs:

def deps do
  [
    {:xml_json, "~> 0.3.0"}
  ]
end

The docs can be found at https://hexdocs.pm/xml_json.

License

MIT Copyright (c) 2020 Ben Brewer

About

Should you convert XML to JSON? Probably not. If you have to though, try a convention based converter.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •  

Languages