Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/hrbrmstr/blackmagic

🎩 Automagically Convert XML to JSON an JSON to XML
https://github.com/hrbrmstr/blackmagic

json-to-xml json-to-xml-converter jsontoxml r r-cyber rstats xml-js xml-to-json xmltojson

Last synced: about 1 month ago
JSON representation

🎩 Automagically Convert XML to JSON an JSON to XML

Awesome Lists containing this project

README

        

---
output: rmarkdown::github_document
editor_options:
chunk_output_type: console
---

# blackmagic

Automagically Convert 'XML' to 'JSON'/'JSON' to 'XML'

## Description

Given a character string of 'XML', an 'xml2' or 'XML' package document, or a 'URL' to retrieve XML content from, convert said 'XML' to 'JSON' using the 'xml-js' 'npm' library by Yousuf Almarzooqi. Also handles the reverse (e.g. 'JSON' to 'XML').

## NOTE

Please reconsider your apparent desire to use this package.

Automagic conversion of XML to JSON (or vice-versa) is _rarely_ a good idea and a path fraught with peril. There are _so many_ options to tweak to ensure you get what you think you want but likely truly want something else entirely, such as a more minimal extract of the original XML file.

Seriously consider parsing the XML/JSON then using `purrr` idioms to extract the data you need into a proper `list` and _then_ call `jsonlite::toJSON()` or `xml2::as_xml_document()` on said `list`.

## What's Inside The Tin

The following functions are implemented:

- `xml_to_json`: Convert XML to JSON
- `json_to_xml`: Convert JSON to XML

## Installation

```{r eval=FALSE}
devtools::install_github("hrbrmstr/blackmagic")
```

```{r message=FALSE, warning=FALSE, error=FALSE, include=FALSE}
options(width=120)
```

## Usage

```{r message=FALSE, warning=FALSE, error=FALSE}
library(blackmagic)

# current verison
packageVersion("blackmagic")

```

### Sample (defaults)

```{r}

xml <- '

Happy
Work
Play
'

cat(xml_to_json(xml))
```

### Sample (`xml2`)

```{r}
cat(xml_to_json(xml2::read_xml(xml)))
```

### Sample (`XML`)

```{r}
cat(xml_to_json(XML::xmlParse(xml)))
```

### Sample (URL + saner tweaks)

```{r}
cat(xml_to_json("https://httpbin.org/xml", spaces = 2, compact = FALSE, ignoreDeclaration = TRUE))
```

### Sample (some saner tweaks)

```{r}
'


Everyday Italian
Giada De Laurentiis
2005
30.00


Harry Potter
J K. Rowling
2005
29.99


Learning XML
Erik T. Ray
2003
39.95

' -> books

cat(xml_to_json(books, spaces = 2, compact = TRUE, ignoreDeclaration = TRUE))
```

### The other way 'round

```{r}
cat(json_to_xml(jsonlite::toJSON(head(mtcars, 2)), spaces=2))
```

### With a URL source

```{r}
cat(json_to_xml("https://httpbin.org/uuid", spaces=2))
```

## Code of Conduct

Please note that this project is released with a [Contributor Code of Conduct](CONDUCT.md). By participating in this project you agree to abide by its terms.