簡體   English   中英

從api屬性接收的JSON對象返回未定義

[英]JSON object recieved from api property returns undefined

對於我正在處理的項目,我正在使用Shopify API,該API允許您從商店中檢索產品和其他信息,並以JSON對象的格式進行檢索。 我能夠從API成功獲取JSON對象,但是當我嘗試訪問JSON對象的屬性時,它返回未定義。 我看了幾篇我將在下面引用的文章,但是這些用戶遇到的問題是諸如需要使用的東西:

JSON.parse()

對於用字符串括起來的JSON對象(不是我的探針),我也嘗試了其他一些解決方法,但是沒有運氣,我本來以為問題是我的代碼需要使用“異步/等待”功能等待來自API的響應,但后來我意識到考慮到我可以毫無問題地接收整個JSON對象本身,這毫無意義。

當我使用時:

request.get(url, {headers})
.then( result => {
console.log(result); // Only accessing object itself
});

我正確接收了JSON對象響應,沒有這樣的錯誤:

     {"products":[{"title":"Test Product 1","body_html":"This is a product that is being tested for retrieval!",
"product_type":"","created_at":"2018-08-21T17:49:07-07:00","handle":"test-product-1","updated_at":"2018-08-21T17:49:07-07:00","published_at":"2018-08-21T17:48:19-07:00","template_suffix":null,"tags":"",
"published_scope":"web","variants":[{"title":"Default Title","price":"5.00","sku":"","position":1,"inventory_policy":"deny",
"compare_at_price":null,"fulfillment_service":"manual","inventory_management":null,"option1":"Default Title","option2":null,"option3":null,
"created_at":"2018-08-21T17:49:07-07:00","updated_at":"2018-08-21T17:49:07-07:00","taxable":true,"barcode":"",
"grams":99790,"image_id":null,"inventory_quantity":1,"weight":220.0,"weight_unit":"lb","old_inventory_quantity":1,
"requires_shipping":true,}],"options":[{"name":"Title","position":1,"values":["Default Title"]}],"images":[],"image":null}]}

但是,當我使用它時,JSON對象屬性返回未定義:

request.get(url, {headers})
    .then( result => {
    console.log(result.products[0]); // Accessing the first item in JSON "products" array
    });

我已經簽出的文章:

無法訪問json對象屬性返回未定義

JSON對象返回未定義的值

JSON對象返回未定義

任何人都可以解釋我的錯誤,或者為什么會這樣? 我很高興編輯我的問題,以包括任何可能有用的代碼/信息。

預先感謝邁克爾

嘗試這個:

console.log("data:", JSON.stringify(result.products[0], null, 2));

console.log將結果打印到控制台。 使用Chrome和開發人員工具,您將看到一個控制台選項-非常適合調試。

JSON.stringify將JSON數據轉換為您可以查看和閱讀的內容。 您也可以轉換數據,然后根據需要拆分。

好,第二個答案。 我無法檢查此內容,因為我沒有您的JSON數據,但是,我會嘗試一些可能與此類似的內容...

data.Items [0]點域

如果數據格式不正確,則采用字符串化方法並將其拆分。 否則,請考慮以下事項:

products":[{"title":"Test Product 1"

variable = products[0].title;

我傾向於使用一種功能來一次性提取所有數據。

function Getv(data){    global.myApp.v = JSON.stringify(data, null, 2); }

那我可以運行這個...

 Getv(data.Items[0]); let splitData = global.myApp.v.split('\"'); let vCount= splitData.length; 

如果對象返回這樣的內容,將無法使用,因為在“產品”標識符之后缺少冒號。 就像盧卡說的那樣,這不是有效的JSON響應

嘗試這個:

var resultJson = JSON.parse(result);

console.log(resultJson.products[0].varname);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM