'Problem combining rawToChar() and write_json()

I have a problem with rawToChar() and write_json() where my result is a .json file that includes \n and \ and cannot be viewed in a "pretty" manner using notebook+. In addition I can't unfold or Uncollapse the result.

My working sequence is:

request <- httr::GET(
   url = "https://myurl",
   httr::content_type("application/json")
 )

existing_distribution.json = jsonlite::prettify(rawToChar(request$content))

write_json(existing_distribution.json, "distribution.json"), pretty = TRUE)

When I open distribution.json with notepad+ I get a single line ...

["{\n    \"ConfigurationStatus\": \"NOT_DEFINED\",\n    \"economicStatus ... blahblah \n}\n"]

Any ideas?



Solution 1:[1]

Let there be a file example.json mocking your API containing

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

This is how to read the file as a raw sequence of bytes, parses it and saves it as prettified json:

library(jsonlite)
library(readr)

read_file_raw("example.json") %>%
  rawToChar() %>%
  parse_json() %>%
  write_json("out.json", pretty = TRUE)

Resulting in file out.json containing:

{
  "glossary": {
    "title": ["example glossary"],
    "GlossDiv": {
      "title": ["S"],
      "GlossList": {
        "GlossEntry": {
          "ID": ["SGML"],
          "SortAs": ["SGML"],
          "GlossTerm": ["Standard Generalized Markup Language"],
          "Acronym": ["SGML"],
          "Abbrev": ["ISO 8879:1986"],
          "GlossDef": {
            "para": ["A meta-markup language, used to create markup languages such as DocBook."],
            "GlossSeeAlso": [
              ["GML"],
              ["XML"]
            ]
          },
          "GlossSee": ["markup"]
        }
      }
    }
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 danlooo