无法从json中提取键/值

时间:2017-01-24 08:02:21

标签: javascript json

在node.js中获取资源,如下所示:

requestify.post('myurl')
.then(function (response) {
    console.log(response);
    console.log(response.body);
});

console.log(响应)给出:

Response {
    code: 200,
    body: '{"guid":"abcd","nounce":"efgh"}' 
}

console.log(response.body)给出:

{"guid":"abcd","nounce":"efgh"}

然而,出于某种原因,我无法访问密钥" guid"或者" nounce"。在这两种情况下,我得到一个未定义。 我用

试过了
console.log(response.body.guid);

console.log(response.body['guid']);

3 个答案:

答案 0 :(得分:1)

正文是字符串,但你希望它是一个对象。只需转换它:

JSON.parse(response.body).guid

答案 1 :(得分:1)

似乎<!DOCTYPE html> <html> <head> <title>Geo City Locator by geoip-db.com</title> </head> <body> <div>Country: <span id="country"></span></div> <div>State: <span id="state"></span></div> <div>City: <span id="city"></span></div> <div>Postal: <span id="postal"></span></div> <div>Latitude: <span id="latitude"></span></div> <div>Longitude: <span id="longitude"></span></div> <div>IP address: <span id="ipv4"></span></div> </body> <script> var country = document.getElementById('country'); var state = document.getElementById('state'); var city = document.getElementById('city'); var postal = document.getElementById('postal'); var latitude = document.getElementById('latitude'); var longitude = document.getElementById('longitude'); var ip = document.getElementById('ipv4'); function callback(data) { country.innerHTML = data.country_name; state.innerHTML = data.state; city.innerHTML = data.city; postal.innerHTML = data.postal; latitude.innerHTML = data.latitude; longitude.innerHTML = data.longitude; ip.innerHTML = data.IPv4; } var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://geoip-db.com/json/geoip.php?jsonp=callback'; var h = document.getElementsByTagName('script')[0]; h.parentNode.insertBefore(script, h); </script> </html>属性的值是一个字符串。您必须将其解析为JSON:

body

答案 2 :(得分:1)

您需要将返回类型设置为

response.writeHead(200, {"Content-Type": "application/json"});

所以你的接收端会在收到时自动将它作为一个对象。 见Responding with a JSON object in NodeJS (converting object/array to JSON string)