xav February 2016

R - Filtering list of nested lists and finding back a higher level key

I am working on parsing a JSON containing API info for several accounts. This data is used in an api wrapper.

[
    {
        "geo":"au",
        "api": [
            {"type":"base_url", "value":"https://api.com"},
            {"type":"key", "value":"f18"},
            {"type":"secret", "value":"569"}
        ],
        "accounts": [
            {"name":"client_AQE","id":"8765","inventory":"all","currency":"AUD"}
       ]
    },{
        "geo":"eu",
        "api": [
            {"type":"base_url", "value":"https://api.com"},
            {"type":"key", "value":"p8c6043"},
            {"type":"secret", "value":"983df5"}
        ],
        "accounts": [
            {"name":"client_UYT","id":"098765","inventory":"all","currency":"GBP"},
            {"name":"client_WER","id":"09098","inventory":"all","currency":"GBP"},
            {"name":"client_OIP","id":"234543","inventory":"all","currency":"EUR"}
        ]
    }
]

When the user give me a "account name" but doesn't specify the "geo", I would like to:

  1. Check if the client only appears once (this can be done with the function below, using rlist)
only_one_client <- function(account_name) {
  return(fromJSON(file=API_INFO_PATH) %>% 
           list.map(accounts) %>% 
           unlist(recursive=F) %>% 
           list.mapv(name) %>% table() %>% extract(account_name) == 1))
}
  1. If the client only appears once, find the "geo" it appears in

This is what I cannot find a way to do

Answers


NicE February 2016

You could transform your JSON into a dataframe holding the each accounts names and the corresponding geo, if data is your the result of fromJSON(file=API_INFO_PATH) you could do:

res <- as.data.frame(do.call(rbind,lapply(data,function(x) cbind(x[["geo"]],do.call(rbind,x[["accounts"]])))))
colnames(res) <- c("geo",colnames(res[,-1]))

res <- merge(res,as.data.frame(table(res$name)),by.x="name",by.y="Var1")

#        name geo     id inventory currency Freq
#1 client_AQE  au   8765       all      AUD    1
#2 client_OIP  eu 234543       all      EUR    1
#3 client_UYT  eu 098765       all      GBP    1
#4 client_WER  eu  09098       all      GBP    1

This basically loops through the list, rbind all the accounts and adds the geo to each row.

You can then use table as in your function to check how many times the name appears and which geo it comes from.

Post Status

Asked in February 2016
Viewed 3,676 times
Voted 9
Answered 1 times

Search




Leave an answer