简体   繁体   中英

Parse a string into json in R

My question may seem trivial, but I am facing issue while parsing a string into json format.

The string I am having is;

[{"Date":"2014-01-01","Turnover":"6761","Shop_Id":"60"},{"Date":"2014-02-01","Turnover":"7254","Shop_Id":"70"},{"Date":"2014-03-01","Turnover":"7539","Shop_Id":"75"},{"Date":"2014-04-01","Turnover":"8211","Shop_Id":"82"}]

I am not able to feed this string in R, while trying to assign this string in an object "v", I am etting this error;

Error: unexpected '[' in "v <- ["

I guess in R, it's not a standard format for a string to be started with a "[" . I tried putting quote on the whole string to make it a character, still it's throwing the same error.

I want to parse this string as a json object, but unable to do the same using fromJSON & toJSON . Parsing this text, I want to make it as dataframe, where I will have all three columns viz;

Date   Turnover  Shop_Id

Please let me know using the mentioned string how can I make a dataframe by parsing the same.

TIA

use single quotes ' instead of double quotes " to store it as string and Bingo!!!

    library(jsonlite)

    jsonStr <- '[{"Date":"2014-01-01","Turnover":"6761","Shop_Id":"60"},{"Date":"2014-02-01","Turnover":"7254","Shop_Id":"70"},{"Date":"2014-03-01","Turnover":"7539","Shop_Id":"75"},{"Date":"2014-04-01","Turnover":"8211","Shop_Id":"82"}]'

   fromJSON(jsonStr)

Output

   Date        Turnover Shop_Id
 1 2014-01-01     6761      60
 2 2014-02-01     7254      70
 3 2014-03-01     7539      75
 4 2014-04-01     8211      82

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM