Search code examples
rjsontwittereda

Loading JSON file into R


I want to insert this JSON file (twitter data) into R and want to make a list like this

enter image description here

but I am getting something like this

enter image description here

My JSON looks something like this (this is just an example)

[{"contributors": null, "truncated": false, "text": "RT @KazmiWajahat: Indian media including @CNNnews18 confirming Pakistan's retaliation at LoC forward areas with heavy firing and shelling w\u2026", "is_quote_status": false}]

Solution

  • You can use jsonlite::fromJSON to parse the JSON file

    Example based on your JSON sample string

    ss <- '[{"contributors": null, "truncated": false, "text": "RT @KazmiWajahat: Indian media including @CNNnews18 confirming Pakistans retaliation at LoC forward areas with heavy firing and shelling w\u2026", "is_quote_status": false}]'
    
    library(jsonlite)
    fromJSON(ss)
    #  contributors truncated
    #1           NA     FALSE
    #                                                                                                                                       text
    #1 RT @KazmiWajahat: Indian media including @CNNnews18 confirming Pakistans retaliation at LoC forward areas with heavy firing and shelling w…
    #  is_quote_status
    #1           FALSE
    

    Here you end up with a data.frame consisting of only one row because of the minimal sample data you gave.

    To take a slightly more complex example from the jsonlite vignette,

    ss <-'[
        {"Name" : "Mario", "Age" : 32, "Occupation" : "Plumber"}, 
        {"Name" : "Peach", "Age" : 21, "Occupation" : "Princess"},
        {"Name" : "Bowser", "Occupation" : "Koopa"}]'
    

    you can see how fromJSON parses the JSON string and returns a data.frame

    fromJSON(ss)
    #    Name Age Occupation
    #1  Mario  32    Plumber
    #2  Peach  21   Princess
    #3 Bowser  NA      Koopa