20

My API returning the JSON value like

[{"UserName":"xxx","Rolename":"yyy"}]

I need Username and RoleName value seperatly i tried JSON.parse but its returning [Object Object] Please help me thanks in advance

3
  • 1
    Voting to close as typo/non-repro/not-usefult-to-others-in-future. The parsing is working just fine; it's just that when you output the first element, you're just outputting the object, not one of its properties. The default toString on an object outputs [object Object] (if it's a plain object). Commented Dec 10, 2017 at 8:30
  • 1
    Welcome to Stack Overflow! Please take the tour, have a look around, and read through the help center, in particular How do I ask a good question? Show us the code that's producing the output you describe. Commented Dec 10, 2017 at 8:48
  • 1
    Possible duplicate of Access / process (nested) objects, arrays or JSON Commented Dec 10, 2017 at 8:50

3 Answers 3

22

Consider the following:

    var str = '[{"UserName":"xxx","Rolename":"yyy"}]'; // your response in a string
    var parsed = JSON.parse(str); // an *array* that contains the user
    var user = parsed[0];         // a simple user
    console.log(user.UserName);   // you'll get xxx
    console.log(user.Rolename);   // you'll get yyy

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

Comments

4

If your data is a string then you need to parse it with JSON.parse() otherwise you don't need to, you simply access it as is.

// if data is not in string format
const data = [{"UserName":"xxx","Rolename":"yyy"}];

const username = data[0].UserName
const rolename = data[0].Rolename

console.log(username)
console.log(rolename)

// if data is in string format
const strData = JSON.parse('[{"UserName":"xxx","Rolename":"yyy"}]');

const Username = strData[0].UserName
const Rolename = strData[0].Rolename

console.log(Username)
console.log(Rolename)

Comments

2

You have an array. Then need to get 0th element very first

This will work

let unps =  JSON.parse('[{"UserName":"xxx","Rolename":"yyy"}]')[0]
console.log(unps.UserName, unps.Rolename);

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.