goryef
goryef

Reputation: 1489

Convert JSON response to map

I have a working code that I am trying to modify.

   let table_specs = {'columns': [ {'name': 'Col1', 'width': 7, ....},
                             {'name': 'Col2', 'width': 8, .....},
                             ........ 
                             {'name': 'Coln', 'width': 30, ....}]}
   foo(table_specs)

   function foo(table_specs){
      for (clmn of table_specs.columns){
        // do something
      }
   }

I am trying to modify the program to have table_specs stored in JSON file and pulled them via ajax call.

z_grid_specs.json

{
"grid1":"{'columns': [ {'name': 'Col1', 'width': 7, ....}, ... {'name': 'Coln', 'wiith': 8, ...}]}"
}

.js on a server

    var pjson_grid = require('../startup/z_grid_specs.json');
    router.get('/grid_specs', (req, res)=> {   
        res.json(pjson_grid)
    })

and i call:

   var table_specs={}
   $.ajax({
    type: 'GET',
    contentType: 'application/json',
    url: '/session/grid_specs',
    success:function(response_data_json) {
        console.log(response_data_json.grid1)
        table_specs = response_data_json.grid1
        foo(table_specs)  
    }
  });

I can verify that ajax called returns a proper data that looks like an array in an original code. But I get an error on a next step:

table_specs.columns is not iterable

I get the same error if I use JSON.stringify(response_data_json.grid1).

If i use JSON.parse(response_data_json.grid1) i get:

Unexpected token ' in JSON at position 1

Upvotes: 1

Views: 67

Answers (1)

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

Remove the double quotes in your JSON file:

{
    "grid1": {'columns': [ {'name': 'Col1', 'width': 7, ....}, ... {'name': 'Coln', 'wiith': 8, ...}]}
}

The grid1 key has a value as a string, and you need it to be an object

Upvotes: 2

Related Questions