从非JSON API网址中提取数据

时间:2016-10-07 01:42:43

标签: javascript json api

我会先设定期望。我知道基本的HTML,并且理解CSS,vbScript和JavaScript,但不是专家,甚至不是中级。

我想从API网址中提取数据,该网址看起来像this ...

并且浏览器返回这些数据......

Domain;Rank;Organic Keywords;Organic Traffic;Organic Cost;Adwords Keywords;Adwords Traffic;Adwords Cost

somedomain.com;31970;26015;35679;252734;0;0;0

如何将这些数据存入JSON文件,以便为其创建JavaScript。

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以拆分字符串,然后手动将部件分配给对象:



var response = "Domain;Rank;Organic Keywords;Organic Traffic;Organic Cost;Adwords Keywords;Adwords Traffic;Adwords Cost;somedomain.com;31970;26015;35679;252734;0;0;0";

var fields = ["Dn", "Rk", "Or", "Ot", "Oc", "Ad", "At", "Ac", null, "v1", "v2", "v3", "v4"];

var data = response.split(";");
var parsedData = {};

fields.forEach(function(fld, i) {
  if (fld) parsedData[fld] = data[i];
});

console.log(parsedData);




答案 1 :(得分:0)

http://codepen.io/anon/pen/yavrYj?editors=1111

用分号分割,将它们分成两个数组(键,值),然后制作json对象

 var data = "Domain; Rank; Organic Keywords; Organic Traffic;Organic Cost;Adwords Keywords;Adwords Traffic; Adwords Cost; somedomain.com;31970;26015;35679;252734;0;0;0"
var values = data.split(";")
var half = values.length / 2
var keys = values.splice(0,half);
var jsonData = {};
for (i = 0; i < keys.length; i++) { 
  jsonData[keys[i]] = values[i]
}

结果是

Object {
   Adwords Cost: "0",
   Organic Keywords: "26015",
   Organic Traffic: "35679",
   Rank: "31970",
  Adwords Keywords: "0",
  Adwords Traffic: "0",
  Domain: " somedomain.com",
  Organic Cost: "252734"
}

您在评论中询问了如何从api获取数据?

如果您使用的是jquery ajax,我猜它会像

$(function() {

  $.ajax("http://api.domain.com/?type=domain_rank&key=somekey&export_columns=Dn,Rk,Or,Ot,Oc,Ad,At,Ac&domain=somedomain..com&database=us",
{
    type: 'get',
    cache: false,
    dataType: 'text',
    contentType: "application/json",
    success: function (data) {
        var values = data.split(";")
var half = values.length / 2
var keys = values.splice(0,half);
var jsonData = {};
for (i = 0; i < keys.length; i++) { 
  jsonData[keys[i]] = values[i]
}

    },
    error: function (xhr, status) {
        console.log(status);
        console.log(xhr.responseText); 
    }
});
});

但是,如果您尝试从其他域上的javascript调用此api,则可能会遇到CORS问题。