Glen
Glen

Reputation: 1772

Save R JSON object with new lines for each record

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")

Upvotes: 4

Views: 2138

Answers (3)

mpadge
mpadge

Reputation: 340

jsonlite::stream_out will only work for flat data.frame objects:

jsonlite::stream_out (list (iris, mtcars)) # error!

More complex structures can be written with intact line breaks simply using writeLines:

x <- jsonlite::toJSON (list (iris, mtcars), pretty = TRUE)
con <- file ("tmp.json")
writeLines (x, con)
close (con)

jsonlite::fromJSON will read this straight back.

Upvotes: 1

sckott
sckott

Reputation: 5903

use jsonlite::stream_out

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

that gives newline delimited JSON or "ndjson"

Upvotes: 10

AidanGawronski
AidanGawronski

Reputation: 2085

This might do the trick:

x2 = strsplit(x, '\\},\\{')
write.table(x2,"tmp.json")

Upvotes: 2

Related Questions