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

How to convert a csv to json with first column as key, and second and third one as values using jsonlite or other package?

Now I obtained:

[
  {
    "full": "f1",
    "semiabrv": "s1",
    "abrv": "a1"
  },
  {
    "full": "f2",
    "semiabrv": "s2",
    "abrv": "a2"
  }
] 

What I expect to be used:

{

"f1": ["s1","a1"],

 "f2": ["s2","a2"]  
}

MWE:

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

fb <- structure(list(full = c("f1", "f2"), semiabrv = c("s1", "s2"), 
abrv = c("a1", "a2")), row.names = 1:2, class = "data.frame")

fb|> 
  jsonlite::toJSON(pretty=TRUE)

Thanks for any idea!

If any other package available, it also ok.

>Solution :

I was about to suggest dataframe="column", but your output assumes a bespoke use of using a value (in one column) as a name (for all other columns combined). For that, we need custom code (but not much).

jsonlite::toJSON(
  do.call(Map,
    c(list(f = function(nm, ...) c(...), fb$full), fb[-1])
  ), pretty = TRUE)
# {
#   "f1": ["s1", "a1"],
#   "f2": ["s2", "a2"]
# } 

While it looks like we provide fb$full as nm= (in the anonfunc) and then discard it, I’m capitalizing on Map‘s tendency to use the first argument to define the names of the output.

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