我目前正在开发一个使用CitySDK模块的项目,该模块可以利用美国人口普查局的API。我可以从API中提取数据,这方面工作正常。我实际上得到的数据看起来像这样:
{
"level": "county",
"zip": "30519",
"variables": [
"income",
"poverty"
],
"api": "acs5",
"year": "2013",
"tract": "050606",
"sublevel": false,
"lat": "+34.0879823",
"lng": "-083.9411706",
"state": "13",
"county": "135",
"blockGroup": "3",
"place": null,
"place_name": null,
"data": [
{
"income": "60445",
"poverty": "113986"
}
]
}
这几乎是我想要的!我遇到的问题是我只想显示两个数据:[{"收入":" 60445","贫困":" 113986"更具体地说,我只想要" 60445"和" 113986"回。我知道它们将作为字符串返回,所以我还需要将它们转换为数字。有谁知道如何做到这一点?这是我的代码:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Test File</title>
</head>
<body>
<input type="number" id="zip" placeholder="Zip"></input>
<input type="number" id="year" placeholder="Year"></input>
<input type="text" id="variables" placeholder="variables"></input>
<!--<input type="number" id="tract" placeholder="tract"></input>-->
<button onclick="data()">Submit</button>
<ul>
<li>population</li>
<li>poverty</li>
<li>median_male_age</li>
<li>median_home_value</li>
</ul>
<p>Please note: The data may take 3-5 seconds to appear.</p>
<p id="data">Data Here:</p>
<script src="js/api.js"></script>
JavaScript的:
var sdk = new CitySDK(); //Create the CitySDK Instance
var census = sdk.modules.census; //Create an instance of the module
census.enable("HIDDEN"); //Enable module
with the API key
//creating the request variable. Please note that I have left in income as
the default variable.
var request = {
"level": "county",
"zip": "",
"variables": [
"income"
],
"api": "acs5",
"year": "",
"tract": ""
};
//Function which will gather data from user and then submit it to the API.
//The API will then return
//the data that was requested.
function data(){
var zip = document.getElementById("zip").value;
var year = document.getElementById("year").value;
var variable = document.getElementById("variables").value;
//var tract = document.getElementById("tract").value;
request.zip = zip;
request.year = year;
request.variables.push(variable);
//The request to gather the actual data.
census.APIRequest(request, function (response) {
//Outputs the raw JSON text
jQuery("#data").text(JSON.stringify(response, null, 4));
//THE BELOW TWO LINES ARE WHERE I HAVE EXPERIMENTED
//jQuery("#data").text(JSON.stringify(response.variables[0], null, 4));
//console.log(JSON.parse(test));
});
}
文本(JSON.stringify(response.variables [0]几乎得到我想要的。在这种情况下,我将输出收入.response.variables [1]将输出贫困或用户输入的任何变量。但是,我不希望看到收入或贫困,但从API变为数字格式的价值。任何帮助将不胜感激!
答案 0 :(得分:0)
正如提到的那样,响应已经是JSON格式(可能)。
如果它像response.data [0]那样.income可以工作。
如果您想摆弄它,请在代码中设置debugger
并打开控制台。
或者它可能不是JSON格式,但服务器将其作为一个大字符串发送回来,在这种情况下,您需要执行类似JSON.parse(response)
的操作以将其置于JSON格式。
要将字符串转换为数字,您可以使用parseInt或parseFloat。
> parseInt("113986")
< 113986
> parseFloat("113986.3939393")
< 113986.3939393