skip to Main Content

I am trying to access merchant name in the following json:

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

the above json formt is returned by an api, I tried access merchant_name value but all I got was none

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);
        })

all I am getting is undefined

3

Answers


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

    Login or Signup to reply.
  2. Try using the [0] first, cause i think its a list.

    console.log(info[0].merchant_name);
    
    Login or Signup to reply.
  3. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search