0

my API is responding as below

{"permissions":
   [{"id":1,"product_id":10,"permission_type":"ADD","name":"Add"}, 
    {"id":2,"product_id":10,"permission_type":"UPDATE","name":"Update"}, 
    {"id":3,"product_id":10,"permission_type":"DELETE","name":"Delete"}
   ]
}

when i use code

const {
    states: { permissions },
  }:any = useUMSStoreContext();

  const myJSON = JSON.stringify(permissions);
  console.log('JSON format', myJSON)

I need to get elements like name or permission_type but not getting success using Typescript. I might be picking wrong way to convert into JSON.

1
  • Do you get any errors? Commented Jan 31, 2023 at 18:38

1 Answer 1

1

Don't use stringify, just use the json object

  const myJSON = JSON.parse(permissions);
  console.log(myJson[0].permissions[0].name); // removed . typo

Simple explanation of format : https://www.json.org/json-en.html

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

3 Comments

const myJSON = JSON.parse(permissions); ---- gives SyntaxError: "[object Object]" is not valid JSON at JSON.parse (<anonymous>)
just a typo because fast replied, correct syntax is : let permissions = '{"permissions":\ [{"id":1,"product_id":10,"permission_type":"ADD","name":"Add"}, \ {"id":2,"product_id":10,"permission_type":"UPDATE","name":"Update"}, \ {"id":3,"product_id":10,"permission_type":"DELETE","name":"Delete"} \ ] \ }'; const myJSON = JSON.parse(permissions); console.log(myJSON.permissions[0].name); console.log(myJSON.permissions[1].permission_type);
typescript playground: typescriptlang.org/…

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.