Anish
Anish

Reputation: 1960

Parsing Json to Data frame in R

I have json data in the following format.

{"abc": "37512", "def": "93145", "ghi": "14160", "jkl": "510842"}

I need to load it in R session as data frame.

col1 col2
abc 37512
def 93145
ghi 14160
jkl 510842

I tried to parse the json using rsjon. Here is my code:

library("rjson")

json_file <- 'finaldata.json'
data <- fromJSON(file=json_file)
data
$abc
[1] "37512"

$def
[1] "93145"

$ghi
[1] "14160"

$jkl
[1] "510842"

This gives me the output as list. How can I get the desired output as data frame.

Upvotes: 0

Views: 226

Answers (1)

akrun
akrun

Reputation: 887851

You can use stack from base R

 stack(data)
 #  values ind
 #1  37512 abc
 #2  93145 def
 #3  14160 ghi
 #4 510842 jkl

or melt from reshape2

 library(reshape2)
 melt(data)

and change the column names

 setNames(melt(data)[,2:1], paste0('col', 1:2))
 #  col1   col2
 #1  abc  37512
 #2  def  93145
 #3  ghi  14160
 #4  jkl 510842

Upvotes: 2

Related Questions