Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save R JSON object with new lines for each record

Tags:

json

r

I'm trying to save a JSON object where each line is a record. How can I save the JSON object so that the number of lines is equal to the number of records (5 in example below)?

  library(jsonlite)
  df=mtcars[1:5,]
  x <- jsonlite::toJSON(df)
  # remove brackets
  x=substr(x,2,nchar(x)-1)
  write_lines(x,"tmp.json")
like image 475
Glen Avatar asked Sep 11 '25 18:09

Glen


2 Answers

use jsonlite::stream_out

df <- mtcars[1:5,]
jsonlite::stream_out(df, file('tmp.json'))

that gives newline delimited JSON or "ndjson"

like image 63
sckott Avatar answered Sep 13 '25 08:09

sckott


This might do the trick:

x2 = strsplit(x, '\\},\\{')
write.table(x2,"tmp.json")
like image 28
AidanGawronski Avatar answered Sep 13 '25 08:09

AidanGawronski