2017-07-02 4 views
1

JSONオブジェクトをフェッチするこの関数があります。JavaScriptでJSON出力をフォーマットするには

function dataFetch(){ 
    const url = "http://www.quotzzy.co/api/quote?key=436587"; 

    fetch(url).then(function(response) { 
     return response.text(); 
    }).then(function(text) { 
     console.log('Request successful', text); 
    }).catch(function(error) { 
     log('Request failed', error) 
    }); 
}; 

JSONオブジェクトのインデックスを個別にHTMLで使用するにはどうすればよいですか?

などは、私の名前(object.name)と私の引用は、このソース(object.source)から(object.text)です。

+1

'JSON.parse'と' JSON.stringify'が文字列とJSON形式の間でひそかするために使用することができます。あなたはresponse.text()を読んでから興味のある特定の属性を読むことができます。 –

+0

私はこれらの両方を使用していますが、私はJSON.parse()を優先します。しかし、どのようにhtmlでの使用のためにそのデータを抽出するのですか、私は成功とループを試した、私は未定義になる。 – RhodosCoder

+0

あなたの質問はかなり幅広いです。あなたはあなたのデータの具体的な例を提供することができますか、結果としてあなたのHTMLで何が起こっているのかを正確に把握できますか? "ロダン" ウィキ: "http://en.wikipedia.org/wiki/Rodin" __proto__ : オブジェクト テキスト : 「これは私が名前を取得JSONオブジェクトの一つである – trincot

答えて

1

このように、Responseオブジェクトのjson()メソッドを直接使用できます。

function dataFetch(){ 
const url = "http://www.quotzzy.co/api/quote?key=436587"; 

fetch(url) 
.then(function(response) { 
if(response.status == 200){ 
    return response.json(); 
}) 
.then(function(responseObj) { 
var text = responseObj.text; 
var authorName = responseObj.author.name; 
var source = responseObj.author.wiki; 
...//access all attributes from the json 
...//assign them to HTML elements 
}) 
.catch(function(error) { 
log('Request failed', error) 
}); 

}; 
+0

それを指摘してくれてありがとう@torazaburo。 –

0

レスポンスをJSONオブジェクトとして変換するには、response.json()を使用できます。 response.json()メソッドは約束を返します。あなたはJSONオブジェクトを取得できることを約束します。

function dataFetch(){ 
const url = "http://www.quotzzy.co/api/quote?key=436587"; 

fetch(url) 
.then(function(response) { 
// return response.text(); // wrong 
return response.json(); // right 
}) 
.then(function(json) { 
console.log('Request successful', json); 
}) 
.catch(function(error) { 
log('Request failed', error) 
}); 

}; 
2

json()を応答に使用してください。オブジェクトの約束を返します。

function dataFetch(){ 
    const url = "http://www.quotzzy.co/api/quote?key=436587"; 

    fetch(url) 
    .then(function(response) { 
     return response.json(); 
    }) 
    .then(function(json) { 
     console.log(json.author.name); 
    }); 
    .catch(function(error) { 
    log('Request failed', error) 
    }); 
} 

より慣用:

function dataFetch(){ 
    const url = "http://www.quotzzy.co/api/quote?key=436587"; 

    fetch(url) 
    .then(response => response.json()) 
    .then(json => console.log(json.author.name, "said", json.text)) 
    .catch(error => log('Request failed', error)); 
} 
+0

json.nameは 'undefined'を返す – RhodosCoder

+1

@RhodosCoder、それは' json.name'が属性ではないからです。 'json.author.name'はです。 JSONを取得したら、他のJSONと同様にそのプロパティを読み取ることができます。 –

+0

torazaburo私はそのES6構文が大好きです:) – RhodosCoder

関連する問題