jhi*_*g15 3 javascript api json getjson web
目前我需要图像的 URL,我正在通过 JSON 文件获取它。由于密钥#开头有一个,我不确定是否获取具有 URL 的密钥。这是JSON:
{
"#text":"https://lastfm-img2.akamaized.net/i/u/34s/3ed37777196a6f2c29c02a1a58a93e4d.png",
"size":"small"
},
{
"#text":"https://lastfm-img2.akamaized.net/i/u/64s/3ed37777196a6f2c29c02a1a58a93e4d.png",
"size":"medium"
}
Run Code Online (Sandbox Code Playgroud)
与其他每次遇到一些 JSON 字符串时一样!
该#是在属性名无效字符,变通方法是在括号标记:«object»[property]- > «array»[index]['#text']。
我们可以使用forEach来提取结果。
var string = '[{"#text":"https://lastfm-img2.akamaized.net/i/u/34s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"small"},{"#text":"https://lastfm-img2.akamaized.net/i/u/64s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"medium"}]';
var parsed = JSON.parse(string);
//parsed is an array, we can loop over it
parsed.forEach(function(obj) {
console.log(obj['#text']);
});Run Code Online (Sandbox Code Playgroud)
如果您可以根据大小从数组中进行选择,那就更漂亮了:
var string = '[{"#text":"https://lastfm-img2.akamaized.net/i/u/34s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"small"},{"#text":"https://lastfm-img2.akamaized.net/i/u/64s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"medium"}]';
function getImageUrlBySize(size, json) {
var parsed = JSON.parse(json);
return parsed.find(function(element) { //modern browsers only (no IE)
return element['size'] == size;
})['#text']; //add text here since find returns the full item
}
console.log(getImageUrlBySize('small', string));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1243 次 |
| 最近记录: |