Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parse simple JSON into dataframe with R

A seemingly simple JSON file that I would like to parse with R:

tmp_extract <- "{\"encrypted_values\":[{\"name_a\":\"value_a\"}, {\"name_b\":\"value_b\"}, {\"name_c\":\"value_c\"}]}"

An attempt with jsonlite::fromJSON produces a dataframe with as many columns as there are names and only a value per column.

tmp_extract |> 
 jsonlite::fromJSON()
$encrypted_values
   name_a  name_b  name_c
1 value_a    <NA>    <NA>
2    <NA> value_b    <NA>
3    <NA>    <NA> value_c

(I also tried tmp_extract |> tidyjson::spread_all() but without success.)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The desired output:

# A tibble: 3 × 2
  name   value  
  <chr>  <chr>  
1 name_a value_a
2 name_b value_b
3 name_c value_c

>Solution :

Try:

tibble::enframe(unlist(unname(jsonlite::fromJSON(tmp_extract, simplifyDataFrame = FALSE))))
# # A tibble: 3 × 2
#   name   value  
#   <chr>  <chr>  
# 1 name_a value_a
# 2 name_b value_b
# 3 name_c value_c
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading