Retrieve JSON user data by jquery

Asked

Viewed 146 times

0

I have a json that I am running through the json-server and this in the address: http://localhost:3000/

Inside it, there is a scope of "users", which I would like to take.

I have the following script I’ve assembled, follows:

$.getJSON(urlParam, function (data) {
        let itens = []
        $.each( data, function (key, val) {
            itens.push( {key, val} )
        })
        return itens
})

I would like to get both a list of users, which is converted to json, both a single user.

Follow my json:

{
  "alunos": [
    {
      "id": 1,
      "nome": "Thiago Cunha"
    },
    {
      "id": 2,
      "nome": "Caroline Cunha"
    },
    {
      "id": 3,
      "nome": "Thalita Cunha"
    }
  ],
  "users": [
    {
      "id": 1,
      "nome": "Thiago Cunha",
      "img": "dist/images/thiago.jpg",
      "status": true
    },
    {
      "id": 2,
      "nome": "Caroline Cunha",
      "img": "dist/images/thiago.jpg",
      "status": true
    },
    {
      "id": 3,
      "nome": "Thalita Cunha",
      "img": "dist/images/thiago.jpg",
      "status": true
    }
  ]
}

Can someone please help me?

  • 3

    is a little confused your question. To catch users do not need to convert anything, it would be var usuarios = data.users, now to catch a single user can make a Function to search in the array by a parameter, id for example, something like: let usuario = usuarios.find(o => o.id === parametroId);

  • 1

    In my humble opinion you could create a different endpoint to search for the individual user record, one for the user search and one for all users. For example: url /users for all users and the url /user/id (where id is the primary key or user identifier) for the individual user record.

1 answer

1

In my humble opinion you could create a different endpoint to search for the individual user record, one for the user search and one for all users. For example: url /users for all users and the url /user/id (where id is the primary key or user identifier) for individual user registration.

  • I’ve already done that. Since the backend system is jsp, I end up using a URL rule defined by Servlets here from the company I work for. But the idea is good and it works here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.