从api属性接收的JSON对象返回未定义

时间:2018-08-22 21:33:51

标签: javascript json node.js express shopify

对于我正在从事的项目,我正在使用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
    });

我已经签出的文章:

cannot access json object property returns undefined

JSON object returns undefined value

JSON objects returns undefined

任何人都可以解释我的错误,或者为什么会这样?我很高兴编辑我的问题,以包括任何可能有用的代码/信息。

预先感谢, 迈克尔

3 个答案:

答案 0 :(得分:0)

尝试一下:

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

console.log将结果打印到控制台。使用Chrome和开发人员工具,您将看到一个控制台选项-非常适合调试。

JSON.stringify将JSON数据转换为您可以查看和阅读的内容。您也可以转换数据,然后根据需要拆分。

好的,第二个答案。我无法检查此内容,因为我没有您的JSON数据,但是,我会尝试一些可能与此类似的内容...

data.Items [0] .field

如果数据格式不正确,则采用字符串化方法并将其拆分。否则,请考虑以下问题:

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; 

答案 1 :(得分:0)

如果对象以这种方式返回,则将不起作用,因为它在“ products”标识符后缺少冒号。就像Luca所说的那样,它不是有效的JSON响应

答案 2 :(得分:0)

尝试一下:

var resultJson = JSON.parse(result);

console.log(resultJson.products[0].varname);
相关问题