如何解析来自 Bigquery 结果的 json 响应?

Posted

技术标签:

【中文标题】如何解析来自 Bigquery 结果的 json 响应?【英文标题】:How to parse json response from Bigquery results? 【发布时间】:2012-11-30 05:48:43 【问题描述】:

我尝试了示例 javascript 代码来调用 Google bigQuery API (https://developers.google.com/bigquery/docs/authorization#client-side-javascript)

Js:

function runQuery() 
   var request = gapi.client.bigquery.jobs.query(
      'projectId': project_id,
      'timeoutMs': '30000',
      'query': 'SELECT TOP(repository_language, 5) as language, COUNT(*) as count FROM [publicdata:samples.github_timeline] WHERE repository_language != "";'
    );
    request.execute(function(response)      
        console.log(response);
        var results = response.result.rows ;
        $('#result_box').html(JSON.stringify(results, null));
    );

大查询返回

["f":["v":"JavaScript","v":"949899"],"f":["v":"Ruby","v":"640659"],"f":["v":"Java","v":"568202"],"f":["v":"Python","v":"484852"],"f":["v":"php","v":"453830"]]

请帮助我如何以 JSON 格式解析上述结果中的值?

"JavaScript": "949899", "Ruby": "640659", "Java": "568202", "Python": "484852", "PHP": "453830" 

【问题讨论】:

【参考方案1】:

评估存在安全风险。

var text = '["f":["v":"JavaScript","v":"949899"],"f":["v":"Ruby","v":"640659"],"f":["v":"Java","v":"568202"],"f":["v":"Python","v":"484852"],"f":["v":"PHP","v":"453830"]]';
myData = JSON.parse(text);
alert(myData[4].f[0].v);​

【讨论】:

【参考方案2】:

http://jsfiddle.net/jv7vm/

var a='["f":["v":"JavaScript","v":"949899"],"f":["v":"Ruby","v":"640659"],"f":["v":"Java","v":"568202"],"f":["v":"Python","v":"484852"],"f":["v":"PHP","v":"453830"]]';

var evala=eval('('+a+')');

for(i=0;i<evala.length;i++)

document.write(evala[i].f[0].v+' '+evala[i].f[1].v+'<br>');

【讨论】:

【参考方案3】:

从下面的javascript得到答案

var total = response.result.totalRows;
var data = [];
for(i=0; i < total; i++)
            data[i]= [ response.rows[i].f[0]["v"], response.rows[i].f[1]["v"] ];
        

 console.log(data);

【讨论】:

以上是关于如何解析来自 Bigquery 结果的 json 响应?的主要内容,如果未能解决你的问题,请参考以下文章

更快地解析 BigQuery JSON 结果

如何在 C# 中动态转换来自 Json.NET 的解析 JSON 结果?

如何在 BigQuery 中解析 JSON 密钥对值?

如何将 JSON 数组中的值解析为 BigQuery 中的列

如何将 bigquery 返回的结果转换为 Json

如何使用 Python 将 bigquery 返回的结果转换为 Json 格式?