Home > Enterprise >  How to show users list in Javascript with parse JSON
How to show users list in Javascript with parse JSON

Time:09-29

I try to put the list of users on the page and call this list of users in JavaScript

my page:

<div id="all_users" data-users='{"name":"jan","userName":"user_jan"}{"name":"jack","userName":"user_jack"}{"name":"jim","userName":"user_jim"}'></div>

I want to call the list of users from the above code in JavaScript

var users = document.querySelector("#all_users");

How can I call the user list like this in javascript?

values: [
          {name: 'jan', userName: 'user_jan'},
          {name: 'jack', userName: 'jack_jan'},
          {name: 'jim', userName: 'jim_jan'},

        ],

update: I changed the above code from double quotes to single quotes. and use

var json = JSON.parse(users.dataset.users);
console.log(json)

show me this error:

Uncaught SyntaxError: Unexpected token { in JSON at position 49

CodePudding user response:

you need to do the following things before to get that result:

  1. Fix your data attribute "data-users" with an array of objects like this:

    data-users='[{"name":"jan","userName":"user_jan"}, {"name":"jack","userName":"user_jack"},{"name":"jim","userName":"user_jim"}]'

  2. to get the data attribute from your querySelector users you need to use .dataset.users to select the data-users attribute.

  3. Use JSON.parse to turn into an object like the following code.

const users = document.querySelector("#all_users");

console.log(JSON.parse(users.dataset.users));
<div id="all_users" data-users='[{"name":"jan","userName":"user_jan"},{"name":"jack","userName":"user_jack"},{"name":"jim","userName":"user_jim"}]'></div>

  • Related