fromJSON, toJSON, square brackets problem

Hi, I'm mainly working with Python, but I decided to use R Shiny for a webapp project.

I've JSON file, I want to read it, and send to an API via POST request.

Example:

{
  "txt_field": "bar",
  "list_field": ["foo"],
  "list_of_dicts": [{ "a": 42, "b": "b" }],
  "list_of_lists": [[2,1,3,4], [3,4,1,2]]
}

The problem is when I use fromJSON, toJSON functions the output is not the same as the initial JSON. txt_field becomes an array "txt_field": ["bar"].

I'm not good at R but I think this about data types in R. Even the a string is 1 length vector with type character. So, I would like to know the reason behind this and more importantly how do I read the json and pass it to an API without changing the original structure.

jsonlite will assume that you dont want to unbox single entry fields,
if you wanted single entries to be unboxed you can use auto_unbox=TRUE param on your toJSON() call.
However, this will unbox list_field 'foo' also...

Thank you. I read that in the documentation too, but as you said it will unbox the other list. So, you are saying there is no way to preserve the actual format?

You can do it.
turns out the fromJSON() function has simplifyVector argument that you can use.

for example:

a_json_char <- '{
  "txt_field": "bar",
  "list_field": ["foo"],
  "list_of_dicts": [{ "a": 42, "b": "b" }],
  "list_of_lists": [[2,1,3,4], [3,4,1,2]]
}'

library(jsonlite)

(rdata <- fromJSON(a_json_char,simplifyVector = FALSE))

(toJSON_output <- toJSON(rdata,auto_unbox = TRUE))

min_orig <- minify(a_json_char)
min_new <- minify(toJSON_output)

identical(min_orig,min_new)
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.