SELECT `justfunctions.eu.convert_json_to_struct`("{ "time": { "new_value": "17:00","old_value": "16:30" }, "price": { "new_value": "1","old_value": "2" } }")
/*--Output--
- time: {"new_value":"17:00","old_value":"16:30"} - price: {"new_value":"1","old_value":"2"}
*/
CREATE OR REPLACE FUNCTION `your_project_id.your_dataset_id.convert_json_to_struct`(`string` string) RETURNS ARRAY<STRUCT<key STRING, value STRING>>
LANGUAGE js AS r'''try {
var obj = JSON.parse(string);
var keys = Object.keys(obj);
var arr = [];
for (i = 0; i < keys.length; i++) {
arr.push({'key': keys[i], 'value': JSON.stringify(obj[keys[i]])});
}
return arr;
} catch(e) {
return '{}';
}
''' OPTIONS ( description = '''Converts a JSON <string> to a STRUCT data type.''' )
JavaScript User Defined Function (JavaScript UDF)
See something wrong? Contact us or report an issue on Github.