Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a newline delimited JSON file from R?

Tags:

python

r

jsonlite

I have a newline delimited (i.e., each JSON object is confined to 1 line in the file):

{"name": "json1"}
{"name": "json2"}
{"name": "json3"}

In Python I can easily read it as follows (I must use the encoding encoding='cp850' to read my real data):

import json

objs = []
with open("testfile.json", encoding='cp850') as f:
    for line in f:
        objs.append(json.loads(line))

How can I do a similar trick in R?

At the end I want to get a data.frame:

library("jsonlite")
library("data.table")

d <- fromJSON("testfile.json", flatten=FALSE)
df <- as.data.frame(d)
like image 592
Fluxy Avatar asked Aug 31 '25 10:08

Fluxy


1 Answers

We can use stream_in from jsonlite

library(jsonlite)
out <- stream_in(file('testfile.json'))
out
#    name
#1 json1
#2 json2
#3 json3

str(out)
#'data.frame':  3 obs. of  1 variable:
#$ name: chr  "json1" "json2" "json3"
like image 83
akrun Avatar answered Sep 02 '25 22:09

akrun