Putting data and titles together in the same JSON structure

Putting data and titles together in the same JSON structure

Sasori7Sasori7 Posts: 26Questions: 10Answers: 0

I have a JSON string like this:
[{"sid":"38","name":"Alex","Last Name":"hori","email":"noz@gmail.com"},{"sid":"59","name":"Andy","Last Name":"numa","email":"tommy@gmail.com"},{"sid":"40","name":"Ann","Last Name":"hama","email":"ohama@gmail.com"}]
Then I made this structure, to fit datatables' needs:
{title: "sid"},{title: "name"},{title: "Last Name"},{title: "email"}
I'm trying to put the titles (column header) at the same time as the data, and nothing is working. The closest I've gotten is an offset of the title and it's column.
$('#example').DataTable( {
data: myList,
columns: [{data:"sid"},{title: "sid"},{data:"name"},{title: "name"},{data:"Last Name"},{title: "Last Name"},{data:"email"},{title: "email"}]
} );

This generates an error: DataTables warning: table id=example - Requested unknown parameter '1' for row 0, column 1.
and DataTables warning: table id=example - Requested unknown parameter '1' for row 0, column 1
and then the columns don't match:

How can I make this work?
__

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599
    edited December 2021 Answer ✓

    The problem is that you need to combine the columns.data and columns.title into the same object, or they'll be treated as different columns - which is what you're seeing.

    So,

    columns: [{data:"sid"},{title: "sid"},{data:"name"},{title: "name"},{data:"Last Name"},{title: "Last Name"},{data:"email"},{title: "email"}]
    

    should be something like:

    columns: [
      { data:"sid", title: "sid" },
      { data:"name", title: "name"},
      ...
    ]
    

    Cheers,

    Colin

  • Sasori7Sasori7 Posts: 26Questions: 10Answers: 0

    Thank you Colin.
    I did that and it worked!
    Then, I tried to make it a variable... and it didn't :(
    cols = '[{ data: "sid", title: "sid"},{ data: "name", title: "name"},{ data: "Last Name", title: "Last Name"},{ data: "email", title: "email"}]';
    data: myList,
    columns: cols

    any ideas?

  • kthorngrenkthorngren Posts: 21,337Questions: 26Answers: 4,954
    edited December 2021

    You are defining cols as a string using '. It should be an array, remove the two '.

    Kevin

  • Sasori7Sasori7 Posts: 26Questions: 10Answers: 0

    ah, I built it as a string...
    :#
    I only used the single quotes to illustrate that.

Sign In or Register to comment.