0

I am developing a website with front-end and back-end separated. I used jquery to send request and get the result as a json object:

{
  "item": [

  ],
  "shop": [

  ],
  "user": [
    {
      "user_id": "9",
      "full_name": "Minh Duc",
      "email": "[email protected]",
      "fb_link": "https:\/\/www.facebook.com\/SieuNhan183",
      "user_name": "Duc",
      "password": "37cd769165eef9ba6ac6b4a0fdb7ef36",
      "level": "0",
      "admin": "0",
      "dob": "1996-03-18",
      "location": "Ho Chi Minh",
      "user_image_url": null
    }
  ]
}

Now i am finding a way to get the data from the object user. How can i do it with javascript?

2
  • $jsonObject.user[0] would be the user object you want. Use . (dot) to access the object property you want Commented Feb 22, 2017 at 15:13
  • There's no such thing as a "JSON Object" Commented Feb 22, 2017 at 15:14

3 Answers 3

3

Complementing @arcs answer, remember that in Javascript you can access members of an object using dot notation (data.user[0].user_id) or square brackets notation. This way:

data['user'][0]['user_id']

this is useful because you can have a 'class' array and then do things like:

['item', 'shop', 'user'].forEach((array) => processArray(data[array][0]));

then you can filter only some classes or do more advanced stuff

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

Comments

2

When you have the data (in example it's in data) use the dot notation to get the node with the user.

The user is an array, so use [] to access a single element, e.g. [0]

var data = {
  "item": [

  ],
  "shop": [

  ],
  "user": [
    {
      "user_id": "9",
      "full_name": "Minh Duc",
      "email": "[email protected]",
      "fb_link": "https:\/\/www.facebook.com\/SieuNhan183",
      "user_name": "Duc",
      "password": "37cd769165eef9ba6ac6b4a0fdb7ef36",
      "level": "0",
      "admin": "0",
      "dob": "1996-03-18",
      "location": "Ho Chi Minh",
      "user_image_url": null
    }
  ]
}


console.log( data.user[0].user_id )

Comments

0

I prefer use square brackets like this :

$jsonObject["user"][0]["user_id"]

but you can use the dot like this :

data.user[0].user_id

is the same thing.

If you want check if property exist you can do it :

if(typeof $jsonObject["user"] !== 'undefined'){
  //do domethings as typeof $jsonObject["user"][0]["user_id"] 
}

If you want get property dinamically you can do it :

const strId = "id";
const strName = "name";

//get user_id
let user_id = $jsonObject[user][0]["user_" + strId ];
//get user_name
let user_name = $jsonObject[user][0]["user_" + strName];

but there isn't very pretty.

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.