0

I have a json object that i want to use.

    {
    "type": "PROVIDER_PAYLOAD",
    "message": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVkOTQ3OTg4N2RlMGRkMDc4ZjEzM2FmNyIsImVtYWlsIjoiYWxzb25nZHVuc3RhbjJAZ21haWwuY29tIiwicm9sZSI6IkNVU1RPTUVSIiwiaWF0IjoxNTcwMDI3MDA4fQ.FcpoBPmhTSX535bNgE2ezCCWsNFPjEhc87hM4y6WadM"
}

so when i try to access it using

console.log("Postback: " + payload.type)

but i get an error of

Postback: undefined

i have looked over some resources on the web and most of them do it this way and it works but i am not sure why mine is not giving the value for type thanks in advance

2
  • 3
    Better Use JSON.parse(payload) before accessing the keys. Commented Oct 2, 2019 at 14:58
  • 1
    @Shubh yah it has worked Commented Oct 2, 2019 at 15:22

1 Answer 1

1

Subh is right. You have to parse the JSON into an object before accessing type using payload.type syntax.

So, let's say you have the following:

let payload = {
    "type": "PROVIDER_PAYLOAD",
    "message": "eyJhbGciOiJIUzWadM"
}

You have to convert it into a JS object using JSON.parse:

let payloadObj = JSON.parse(payload); 

Now, if you do payloadObj.type, you should be fine.

console.log(payloadObj.type); // PROVIDER_PAYLOAD

It should work fine.

UPDATE: ERROR: SyntaxError: Unexpected token a in JSON at position 0

If you are getting this error, try following to Parse the payload.

let payloadObj = JSON.parse(JSON.stringify(payload))

It should solve the problem for you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.