I want to get from a data.table like this
temp <- data.table(data = list(data.table(a = 1:2,b=1:2)), type = "A")
data
type
<data.table[2x2]>
A
to a JSON like this
{
"group":
{
"data": [
{
"a": 1,
"b": 1
},
{
"a": 2,
"b": 2
}
],
"type": "A"
}
}
The Problem is I always end up with an additional array "[" for group.
What I have tried is tidyr::nest and
temp2 <- temp[, list(group=list(.SD))]
jsonlite::toJSON(temp2,pretty = TRUE, auto_unbox = TRUE)
temp3 <- temp[, (list(group=list(as.list(.SD))))]
jsonlite::toJSON(temp3,pretty = TRUE, auto_unbox = TRUE)
Is there an "easy" solution for my problem?
Thanks
edit more complex example
temp <-
data.table(
id1 = 1:6,
id2 = c(rep("A", 2), rep("B", 2), rep("C", 2)),
data = rep(list(data.table(
a = 1:2, b = 1:2
)), 6),
type = "test"
)
nest1 <- temp[, list(list(.SD)),by=.(id1,id2)] %>% setnames("V1","group")
nest1[, type:="B"]
nest2 <- nest1[, list(list(.SD)),by=.(id2)] %>% setnames("V1","data")
nest2[, type:="C"]
nest3 <- nest2[, list(list(.SD)),by=.(id2)] %>% setnames("V1","group")
jsonlite::toJSON(nest3, pretty = TRUE)
desired output (shortend):
Group should only contain objects and no arrays
[
{
"id2": "A",
"group": {
"data": [
{
"id1": 1,
"group": {
"data": [
{
"a": 1,
"b": 1
},
{
"a": 2,
"b": 2
}
],
"type": "test"
},
"type": "B"
},
{
"id1": 2,
"group": {
"data": [
{
"a": 1,
"b": 1
},
{
"a": 2,
"b": 2
}
],
"type": "test"
},
"type": "B"
}
],
"type": "C"
}
},
{
"id2": "B",
"group": {
"data": [],
"type": "C"
}
}
]
We could use jq to do the unboxing as a post-processing step, since jsonlite doesn't seem to allow for this specific use case:
jsonlite::toJSON(nest3, pretty = TRUE) %>%
jqr::jq('walk(if type=="array" and length==1 then .[0] else . end)')
The jq bit is taken from jq ~ is there a better way to collapse single object arrays?
I have a data frame like below:
df <- data.frame(child = c('item3-1-1','item3-1-2','item3-2','item3-1','item2-1','item2-2','item1'),parent = c('item3-1','item3-1','item3','item3','item2','item2',''))
I want to convert this dataframe in below format:
choices <-
list(
list(id = 1, title = "item1"),
list(id = 2, title = "item2",
subs = list(
list(id = 21, title = "item2-1"),
list(id = 22, title = "item2-2")
)
),
list(id = 3, title = "item3",
subs = list(
list(id = 31, title = "item3-1", isSelectable = FALSE,
subs = list(
list(id = 311, title = "item3-1-1"),
list(id = 312, title = "item3-1-2")
)
),
list(id = 32, title = "item3-2")
)
)
)
I need the nested list with option of 'subs' to traverse the tree drop-down list.
Is there any function or method by which I can achieve this as I have huge dataset.
Here is a function which generates the nested list. The id are not the same but anyway we do not use them in ComboTree (but they are required).
dat <- data.frame(
item = c("item1", "item2", "item2-1", "item2-2", "item3", "item3-1",
"item3-1-1", "item3-1-2", "item3-2"),
parent = c("root", "root", "item2", "item2", "root", "item3",
"item3-1", "item3-1", "item3"),
stringsAsFactors = FALSE
)
makeChoices <- function(dat){
f <- function(parent, id = "id"){
i <- match(parent, dat$item)
title <- dat$item[i]
subs <- dat$item[dat$parent==title]
if(length(subs)){
list(
title = title,
id = paste0(id,"-",i),
subs = lapply(subs, f, id = paste0(id,"-",i))
)
}else{
list(title = title, id = paste0(id,"-",i))
}
}
lapply(dat$item[dat$parent == "root"], f)
}
choices <- makeChoices(dat)
> jsonlite::toJSON(choices, auto_unbox = TRUE, pretty = TRUE)
[
{
"title": "item1",
"id": "id-1"
},
{
"title": "item2",
"id": "id-2",
"subs": [
{
"title": "item2-1",
"id": "id-2-3"
},
{
"title": "item2-2",
"id": "id-2-4"
}
]
},
{
"title": "item3",
"id": "id-5",
"subs": [
{
"title": "item3-1",
"id": "id-5-6",
"subs": [
{
"title": "item3-1-1",
"id": "id-5-6-7"
},
{
"title": "item3-1-2",
"id": "id-5-6-8"
}
]
},
{
"title": "item3-2",
"id": "id-5-9"
}
]
}
]
When receiving a product updated hook from WooCommerce, the payload contains a 'variations' array, which, however, only contains the IDs of the variations that belong to the updated product.
How can I send the actual variation objects along with the product updated payload, instead of only the IDs of the variation (this way, I wouldn't need to send another request to the variations resource of the REST API to fetch them).
Thanks!
You need to hook woocommerce_webhook_payload to build the payload. The details of the product variation are stored in variations_objs.
// Hook to the webhook build process and add your variations objects.
add_filter( 'woocommerce_webhook_payload', 'dolly_woocommerce_webhook_payload', 10, 4 );
function dolly_woocommerce_webhook_payload( $payload, $resource, $resource_id, $id ) {
// Remove the filter to eliminate the recursion calls.
remove_filter( 'woocommerce_webhook_payload', 'dolly_woocommerce_webhook_payload', 10 );
// Create a WC_Webhook class with the webhook id.
$wc_webhook = new WC_Webhook( $id );
// Bail early if the resource is not product.
if ( 'product' !== $resource ) {
return $payload;
}
// Bail early if the product type is not variable.
$product = new WC_Product( $resource_id );
if ( 'variable' === $product->get_type() ) {
return $payload;
}
// Build the payload of each product variation.
$variations = $payload['variations'];
foreach( $variations as $variation ) {
$variations_objs[] = $wc_webhook->build_payload( $variation );
}
// Add the varitions to the payload.
$payload['variations_objs'] = $variations_objs;
// Add the filter again and return the payload.
add_filter( 'woocommerce_webhook_payload', 'dolly_woocommerce_webhook_payload', 10, 4 );
return $payload;
}
Here is the data sent by the webhooks.
{
"id" : 94,
"name" : "Nepali Shirt",
"slug" : "nepali-shirt",
"permalink" : "http://online-users.test/product/nepali-shirt/",
"date_created" : "2019-07-14T05:12:52",
"date_created_gmt" : "2019-07-14T05:12:52",
"date_modified" : "2019-07-18T07:52:36",
"date_modified_gmt" : "2019-07-18T07:52:36",
"type" : "variable",
"status" : "publish",
"featured" : false,
"catalog_visibility" : "visible",
"description" : "<p>hello tamang hhh jjjjj sfsfsd hllk ljlkjkl jljk ljlkjkl kjlkjlk jlkj dgdfg jkl ljlk sdfdsf sfsd sfdds</p>\n",
"short_description" : "",
"sku" : "",
"price" : "205",
"regular_price" : "",
"sale_price" : "",
"date_on_sale_from" : null,
"date_on_sale_from_gmt": null,
"date_on_sale_to" : null,
"date_on_sale_to_gmt" : null,
"price_html" : "<span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">£</span>205.00</span> – <span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">£</span>500.00</span>",
"on_sale" : false,
"purchasable" : true,
"total_sales" : 0,
"virtual" : false,
"downloadable" : false,
"downloads" : [],
"download_limit" : -1,
"download_expiry" : -1,
"external_url" : "",
"button_text" : "",
"tax_status" : "taxable",
"tax_class" : "",
"manage_stock" : false,
"stock_quantity" : null,
"in_stock" : true,
"backorders" : "no",
"backorders_allowed" : false,
"backordered" : false,
"sold_individually" : false,
"weight" : "",
"dimensions" : {
"length": "",
"width" : "",
"height": ""
},
"shipping_required": true,
"shipping_taxable" : true,
"shipping_class" : "",
"shipping_class_id": 0,
"reviews_allowed" : true,
"average_rating" : "0.00",
"rating_count" : 0,
"related_ids" : [
82,
80
],
"upsell_ids" : [],
"cross_sell_ids": [],
"parent_id" : 0,
"purchase_note" : "",
"categories" : [
{
"id" : 15,
"name": "Uncategorized",
"slug": "uncategorized"
}
],
"tags" : [],
"images": [
{
"id" : 0,
"date_created" : "2019-07-18T07:53:30",
"date_created_gmt" : "2019-07-18T07:53:30",
"date_modified" : "2019-07-18T07:53:30",
"date_modified_gmt": "2019-07-18T07:53:30",
"src" : "http://online-users.test/wp-content/uploads/woocommerce-placeholder-324x324.png",
"name" : "Placeholder",
"alt" : "Placeholder",
"position" : 0
}
],
"attributes": [
{
"id" : 1,
"name" : "Color",
"position" : 0,
"visible" : true,
"variation": true,
"options" : [
"Blue",
"Gray",
"Red"
]
}
],
"default_attributes": [
{
"id" : 1,
"name" : "Color",
"option": "blue"
}
],
"variations": [
96,
97,
98
],
"grouped_products": [],
"menu_order" : 0,
"meta_data" : [
{
"id" : 1103,
"key" : "pageview",
"value": "1"
}
],
"store": {
"id" : 1,
"name" : "admin",
"shop_name": "WordPress Biratnagar",
"url" : "http://online-users.test/store/admin/",
"address" : {
"street_1": "Haatkhola",
"street_2": "",
"city" : "Biratnagar",
"zip" : "977",
"country" : "NP",
"state" : "BAG"
}
},
"variations_objs": [
{
"id" : 96,
"name" : "Nepali Shirt - Blue",
"slug" : "nepali-shirt-blue",
"permalink" : "http://online-users.test/product/nepali-shirt/?attribute_pa_color=blue",
"date_created" : "2019-07-14T05:12:12",
"date_created_gmt" : "2019-07-14T05:12:12",
"date_modified" : "2019-07-18T06:52:07",
"date_modified_gmt" : "2019-07-18T06:52:07",
"type" : "variation",
"status" : "publish",
"featured" : false,
"catalog_visibility" : "visible",
"description" : "",
"short_description" : "",
"sku" : "",
"price" : "205",
"regular_price" : "205",
"sale_price" : "",
"date_on_sale_from" : null,
"date_on_sale_from_gmt": null,
"date_on_sale_to" : null,
"date_on_sale_to_gmt" : null,
"price_html" : "<span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">£</span>205.00</span>",
"on_sale" : false,
"purchasable" : true,
"total_sales" : "0",
"virtual" : false,
"downloadable" : false,
"downloads" : [],
"download_limit" : -1,
"download_expiry" : -1,
"external_url" : "",
"button_text" : "",
"tax_status" : "taxable",
"tax_class" : "",
"manage_stock" : false,
"stock_quantity" : null,
"in_stock" : true,
"backorders" : "no",
"backorders_allowed" : false,
"backordered" : false,
"sold_individually" : false,
"weight" : "",
"dimensions" : {
"length": "",
"width" : "",
"height": ""
},
"shipping_required": true,
"shipping_taxable" : true,
"shipping_class" : "",
"shipping_class_id": 0,
"reviews_allowed" : false,
"average_rating" : "0.00",
"rating_count" : 0,
"related_ids" : [],
"upsell_ids" : [],
"cross_sell_ids" : [],
"parent_id" : 94,
"purchase_note" : "",
"categories" : [],
"tags" : [],
"images" : [
{
"id" : 0,
"date_created" : "2019-07-18T07:54:12",
"date_created_gmt" : "2019-07-18T07:54:12",
"date_modified" : "2019-07-18T07:54:12",
"date_modified_gmt": "2019-07-18T07:54:12",
"src" : "http://online-users.test/wp-content/uploads/woocommerce-placeholder-324x324.png",
"name" : "Placeholder",
"alt" : "Placeholder",
"position" : 0
}
],
"attributes": [
{
"id" : 1,
"name" : "Color",
"option": "Blue"
}
],
"default_attributes": [],
"variations" : [],
"grouped_products" : [],
"menu_order" : 1,
"meta_data" : [],
"store" : {
"id" : 1,
"name" : "admin",
"shop_name": "WordPress Biratnagar",
"url" : "http://online-users.test/store/admin/",
"address" : {
"street_1": "Haatkhola",
"street_2": "",
"city" : "Biratnagar",
"zip" : "977",
"country" : "NP",
"state" : "BAG"
}
}
},
{
"id" : 97,
"name" : "Nepali Shirt - Gray",
"slug" : "nepali-shirt-gray",
"permalink" : "http://online-users.test/product/nepali-shirt/?attribute_pa_color=gray",
"date_created" : "2019-07-14T05:12:13",
"date_created_gmt" : "2019-07-14T05:12:13",
"date_modified" : "2019-07-14T05:12:44",
"date_modified_gmt" : "2019-07-14T05:12:44",
"type" : "variation",
"status" : "publish",
"featured" : false,
"catalog_visibility": "visible",
"description" : "",
"short_description": "",
"sku": "",
"price": "300",
"regular_price": "300",
"sale_price": "",
"date_on_sale_from": null,
"date_on_sale_from_gmt": null,
"date_on_sale_to": null,
"date_on_sale_to_gmt": null,
"price_html": "<span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">£</span>300.00</span>",
"on_sale": false,
"purchasable": true,
"total_sales": "0",
"virtual": false,
"downloadable": false,
"downloads": [],
"download_limit": -1,
"download_expiry": -1,
"external_url": "",
"button_text": "",
"tax_status": "taxable",
"tax_class": "",
"manage_stock": false,
"stock_quantity": null,
"in_stock": true,
"backorders": "no",
"backorders_allowed": false,
"backordered": false,
"sold_individually": false,
"weight": "",
"dimensions": {
"length": "",
"width": "",
"height": ""
},
"shipping_required": true,
"shipping_taxable": true,
"shipping_class": "",
"shipping_class_id": 0,
"reviews_allowed": false,
"average_rating": "0.00",
"rating_count": 0,
"related_ids": [],
"upsell_ids": [],
"cross_sell_ids": [],
"parent_id": 94,
"purchase_note": "",
"categories": [],
"tags": [],
"images": [
{
"id": 0,
"date_created": "2019-07-18T07:54:13",
"date_created_gmt": "2019-07-18T07:54:13",
"date_modified": "2019-07-18T07:54:13",
"date_modified_gmt": "2019-07-18T07:54:13",
"src": "http://online-users.test/wp-content/uploads/woocommerce-placeholder-324x324.png",
"name": "Placeholder",
"alt": "Placeholder",
"position": 0
}
],
"attributes": [
{
"id": 1,
"name": "Color",
"option": "Gray"
}
],
"default_attributes": [],
"variations": [],
"grouped_products": [],
"menu_order": 2,
"meta_data": [],
"store": {
"id": 1,
"name": "admin",
"shop_name": "WordPress Biratnagar",
"url": "http://online-users.test/store/admin/",
"address": {
"street_1": "Haatkhola",
"street_2": "",
"city": "Biratnagar",
"zip": "977",
"country": "NP",
"state": "BAG"
}
}
},
{
"id": 98,
"name": "Nepali Shirt - Red",
"slug": "nepali-shirt-red",
"permalink": "http://online-users.test/product/nepali-shirt/?attribute_pa_color=red",
"date_created": "2019-07-14T05:12:14",
"date_created_gmt": "2019-07-14T05:12:14",
"date_modified": "2019-07-14T05:42:04",
"date_modified_gmt": "2019-07-14T05:42:04",
"type": "variation",
"status": "publish",
"featured": false,
"catalog_visibility": "visible",
"description": "",
"short_description": "",
"sku": "",
"price": "500",
"regular_price": "500",
"sale_price": "",
"date_on_sale_from": null,
"date_on_sale_from_gmt": null,
"date_on_sale_to": null,
"date_on_sale_to_gmt": null,
"price_html": "<span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">£</span>500.00</span>",
"on_sale": false,
"purchasable": true,
"total_sales": "0",
"virtual": false,
"downloadable": false,
"downloads": [],
"download_limit": -1,
"download_expiry": -1,
"external_url": "",
"button_text": "",
"tax_status": "taxable",
"tax_class": "",
"manage_stock": false,
"stock_quantity": null,
"in_stock": true,
"backorders": "no",
"backorders_allowed": false,
"backordered": false,
"sold_individually": false,
"weight": "",
"dimensions": {
"length": "",
"width": "",
"height": ""
},
"shipping_required": true,
"shipping_taxable": true,
"shipping_class": "",
"shipping_class_id": 0,
"reviews_allowed": false,
"average_rating": "0.00",
"rating_count": 0,
"related_ids": [],
"upsell_ids": [],
"cross_sell_ids": [],
"parent_id": 94,
"purchase_note": "",
"categories": [],
"tags": [],
"images": [
{
"id": 0,
"date_created": "2019-07-18T07:54:14",
"date_created_gmt": "2019-07-18T07:54:14",
"date_modified": "2019-07-18T07:54:14",
"date_modified_gmt": "2019-07-18T07:54:14",
"src": "http://online-users.test/wp-content/uploads/woocommerce-placeholder-324x324.png",
"name": "Placeholder",
"alt": "Placeholder",
"position": 0
}
],
"attributes": [
{
"id": 1,
"name": "Color",
"option": "Red"
}
],
"default_attributes": [],
"variations": [],
"grouped_products": [],
"menu_order": 3,
"meta_data": [],
"store": {
"id": 1,
"name": "admin",
"shop_name": "WordPress Biratnagar",
"url": "http://online-users.test/store/admin/",
"address": {
"street_1": "Haatkhola",
"street_2": "",
"city": "Biratnagar",
"zip": "977",
"country": "NP",
"state": "BAG"
}
}
}
]
}
I am trying to convert a heavily nested json into a proper data frame (proper by tidy standards). An MWE of the json is copied at the end of the question, as I wanted to make sure it captured every element of the json.
I've tried:
library(jsonlite)
library(tidyverse)
dat <- jsonlite::fromJSON('data_toy.json') %>% pluck(1) %>% imap_dfr(~mutate(.x, department = .y))
but this returns:
Error: Columns `time_spent`, `school_breakdown`, `reason_for_taking_course`, `student_years`, `interest_before` must be 1d atomic vectors or lists
I've also tried:
dat <- jsonlite::fromJSON('data_toy.json', simplifyVector = FALSE,
simplifyDataFrame = FALSE, flatten=FALSE)
dat.df <- map_df(dat, ~{
flatten_df(.x[[1]]) %>%
dplyr::mutate(department = names(.x)[1])
})
but this returns:
Error in bind_rows_(x, .id) : Argument 3 must be length 1, not 0
How can I convert this to a data frame?
Data file (data_toy.json):
{
"department": {
"BME": [
{
"course_name": "BMD_ENG_250-0_20: Thermodynamics",
"instructor": "Neha Kamat",
"time_spent": {},
"school_breakdown": {
"Education & SP": 0,
"Communication": 0,
"Graduate School": 0,
"KGSM": 0
},
"reason_for_taking_course": {
"Distribution requirement": 0,
"Major/Minor requirement": 53
},
"student_years": {
"Freshman": 5,
"Sophomore": 37
},
"interest_before": {
"1-Not interested at all": 1,
"2": 5
},
"comments": [
"is amazing and you will love her!",
"Prof. is so nice"
],
"instructor_gender": "F"
},
{
"course_name": "BMD_ENG_250-0_20: Thermodynamics",
"instructor": "Neha Kamat",
"time_spent": {},
"school_breakdown": {
"Education & SP": 0,
"Communication": 0,
"Graduate School": 0,
"KGSM": 0
},
"reason_for_taking_course": {
"Distribution requirement": 0,
"Major/Minor requirement": 53
},
"student_years": {
"Freshman": 5,
"Sophomore": 37
},
"interest_before": {
"1-Not interested at all": 1,
"2": 5
},
"comments": [
"is amazing and you will love her!",
"Prof. is so nice"
],
"instructor_gender": "F"
}
],
"LING": [
{
"course_name": "BMD_ENG_250-0_20: Thermodynamics",
"instructor": "Neha Kamat",
"time_spent": {},
"school_breakdown": {
"Education & SP": 0,
"Communication": 0,
"Graduate School": 0,
"KGSM": 0
},
"reason_for_taking_course": {
"Distribution requirement": 0,
"Major/Minor requirement": 53
},
"student_years": {
"Freshman": 5,
"Sophomore": 37
},
"interest_before": {
"1-Not interested at all": 1,
"2": 5
},
"comments": [
"is amazing and you will love her!",
"Prof. is so nice"
],
"instructor_gender": "F"
},
{
"course_name": "BMD_ENG_250-0_20: Thermodynamics",
"instructor": "Neha Kamat",
"time_spent": {},
"school_breakdown": {
"Education & SP": 0,
"Communication": 0,
"Graduate School": 0,
"KGSM": 0
},
"reason_for_taking_course": {
"Distribution requirement": 0,
"Major/Minor requirement": 53
},
"student_years": {
"Freshman": 5,
"Sophomore": 37
},
"interest_before": {
"1-Not interested at all": 1,
"2": 5
},
"comments": [
"is amazing and you will love her!",
"Prof. is so nice"
],
"instructor_gender": "F"
}
]
}
}
Using flatten = TRUE seems to be the key here:
dat <- jsonlite::fromJSON('data_toy.json', flatten = TRUE)[[1]]
dat %>% bind_rows() %>% mutate(department = rep(names(dat), map_dbl(dat, nrow)))