15

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

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
karthi
  • 173
  • 1
  • 1
  • 6
  • 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). – T.J. Crowder Dec 10 '17 at 08:30
  • 1
    Welcome to Stack Overflow! Please take the [tour], have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Show us the code that's producing the output you describe. – T.J. Crowder Dec 10 '17 at 08:48
  • 1
    Possible duplicate of [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – JJJ Dec 10 '17 at 08:50

3 Answers3

20

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
Lajos Gallay
  • 1,169
  • 7
  • 16
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)
Sapinder
  • 193
  • 2
  • 14
codejockie
  • 9,020
  • 4
  • 40
  • 46
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);
Shalitha Suranga
  • 1,138
  • 8
  • 24