Access JSON对象,该对象以JavaScript数组的形式存在。

huangapple go评论53阅读模式
英文:

how to access json object that is in a form of array in javascript

问题

以下是您要翻译的内容:

"我是JavaScript的新手,需要帮助访问由API返回的数据中的数组元素。下面是我想要操作的数据示例:

[{"merchant_id":"90151","merchant_name":"Wimpy"}]

上述JSON格式是由API返回的,我尝试访问merchant_name的值,但由于缺乏知识,我得到了空值。

下面是我的尝试:

fetch("http://127.0.0.1:8000/vcl/retrieve/"+url, {
          method: "GET",
          headers: {
            "Content-Type": "application/json"
          },
        }).then((res) => res.json()).then((response) => {  
          console.log (response);
          const data = JSON.stringify(response);
          const info = JSON.parse(data);
          var merchant_name = info.merchant_name;
          console.log(merchant_name);
        })

我得到的值是undefined,而不是商家名称。"

英文:

I am new in javascript I need help in accessing an elements of an array from the data returned by an API. below is an example of the data I want to manipulate:

[{"merchant_id":"90151","merchant_name":"Wimpy"}]

the above json format is returned by an api, I tried to access merchant_name value but I was getting nothing due to lack of knowledge.

below is what I tried:

fetch("http://127.0.0.1:8000/vcl/retrieve/"+url, {
          method: "GET",
          headers: {
            "Content-Type": "application/json"
          },
        }).then((res) => res.json()).then((response) => {  
          console.log (response);
          const data = JSON.stringify(response);
          const info = JSON.parse(data);
          var merchant_name = info.merchant_name;
          console.log(merchant_name);
        })

I am getting undefined as the value instead of the merchant name

答案1

得分: 1

尝试首先使用 [0],因为我认为它是一个列表。

console.log(info[0].merchant_name);

英文:

Try using the [0] first, cause i think its a list.

console.log(info[0].merchant_name);

答案2

得分: 0

你可以这样做:info.pop().merchant_name

英文:

Not sure why you stringify and parse, but you can do e.g. info.pop().merchant_name.

答案3

得分: 0

这个答案解释了为什么你不能简单地使用 info.merchant_name

不能访问 merchant_name 的原因是响应返回的是一个包含一个对象的数组,而不是直接返回一个对象。

因为它返回一个数组,所以你需要在读取对象属性之前访问数组的第一个索引(从零开始)。

示例:

let merchant_name = info[0].merchant_name;
console.log(merchant_name);
英文:

This answer explains why you simply cannot use info.merchant_name.

The reason you are not able to access the merchant_name is because the response is returning an array with one object instead of simply returning an object.

Since it is returning an array, you need to access the first index of the array (it starts at zero) before you can read the object properties.

Example:

let merchant_name = info[0].merchant_name;
console.log(merchant_name);

huangapple
  • 本文由 发表于 2023年4月13日 22:47:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76006847.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定