bxio
bxio

Reputation: 43

Parsing JSON data into table

I have a JSON string like so:

{"In Progress":1,"Re-assigned":0,"Completed":0,"Submitted":1,"Reviewed":0,"Assigned":0,"Unassigned":0,"Draft":1,"In Review":0}

I want to put it into a simple table formatted like so:

<table>
  <thead>
    <tr>
      <th>State Name</th>
      <th>Count</th>
    </tr>
  </thead>

What do I put as the <tr> and <td> classes?

Upvotes: 2

Views: 1954

Answers (3)

Shamik
Shamik

Reputation: 36

To add to Ed B's answer,

You should reformat the JSON into an array that looks like this: [ {'StateName': 'In Progress', 'Count': 1}, ... ]

You can make this change in this source of the JSON if you have access or parse it in your Angular code. Then, you can create a controller with Angular:

app.controller('StateController', function() { this.states = your_json_array; }); and add the controller to your HTML with <table ng-controller='StateController as stateCtrl'> and <tr ng-repeat='state in stateCtrl.states' as well as the bindings ({{...}}) shown by Ed B.

Upvotes: -1

craigb
craigb

Reputation: 16907

Where your $scope looks something like this:

$scope.data = { "In Progress":1,"Re-assigned":0,"Completed":0,"Submitted":1 };

You need to use a slightly different for expression in the ng-repeat:

<tr ng-repeat="(key, val) in data">
    <td>{{ key }}</td>
    <td>{{ val }}</td>
</tr>

see: https://docs.angularjs.org/api/ng/directive/ngRepeat for examples of the alternative repeat expressions you can use. (in this case you are iterating over keys and values on a single object, not over an array of objects as more common case)

Upvotes: 3

Ed B
Ed B

Reputation: 859

I'm not really sure how that JSON object relates to the table that you're trying to create, but normally what you'd do is use the ng-repeat directive to loop through a JSON array like so:

<table>
  <thead>
    <tr>
      <th>State Name</th>
      <th>Count</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="state in states">
      <td>{{ state.StateName }} </td>
      <td>{{ state.Count }} </td>
    </tr>
  </tbody>
</table>

where 'states' in ng-repeat="state in states" refers to the JSON object that you're passing in from your Angular Controller

Upvotes: -1

Related Questions