我正在关注https://cloud.google.com/bigquery/create-simple-app-api#bigquery-simple-app-java中给出的示例,以获取BigQuery API的查询结果。
TableResult result = queryJob.getQueryResults();
它以TableResults类型返回结果,但我需要以json格式得到结果。
TableResult{rows=[[FieldValue{attribute=PRIMITIVE, value=(...)},
FieldValue{attribute=PRIMITIVE, value=(...)},
FieldValue{attribute=PRIMITIVE, value=(...)},
FieldValue{attribute=PRIMITIVE, value=(...)},
FieldValue{attribute=PRIMITIVE, value=(...)},
FieldValue{attribute=PRIMITIVE, value=(...)},
FieldValue{attribute=PRIMITIVE, value=(...)}],(...)
如何将TableResults类型的结果转换为json,甚至csv?
答案 0 :(得分:1)
要将表格中的行转换为JSON,您可以使用函数TO_JSON_STRING
[1]。
要获取带格式的JSON,您需要将参数“true”传递给函数。
新查询如下所示:
#standardSQL
“SELECT TO_JSON_STRING(t,true)"
+ "FROM (
SELECT CONCAT('https://stackoverflow.com/questions/', CAST(id as STRING)) as url, "
+ "view_count "
+ "FROM `bigquery-public-data.stackoverflow.posts_questions` "
+ "WHERE tags like '%google-bigquery%' "
+ "ORDER BY favorite_count DESC LIMIT 10) as t”
输出:
TableResult{rows=[[FieldValue{attribute=PRIMITIVE, value={
"url": "https://stackoverflow.com/questions/6607552",
"view_count": 24524
}}], [FieldValue{attribute=PRIMITIVE, value={
"url": "https://stackoverflow.com/questions/20349189",
"view_count": 4298
}}], [FieldValue{attribute=PRIMITIVE, value={
"url": "https://stackoverflow.com/questions/22734777",
"view_count": 7940
}}], [FieldValue{attribute=PRIMITIVE, value={
"url": "https://stackoverflow.com/questions/27537720",
"view_count": 2039
(...)