简体   繁体   English

将 JSON 响应转换为映射

[英]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.我正在尝试修改程序以将 table_specs 存储在 JSON 文件中并通过 ajax 调用提取它们。

z_grid_specs.json z_grid_specs.json

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

.js on a server服务器上的 .js

    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.我可以验证调用的 ajax 返回了一个正确的数据,该数据在原始代码中看起来像一个数组。 But I get an error on a next step:但是我在下一步中遇到错误:

table_specs.columns is not iterable table_specs.columns 不可迭代

I get the same error if I use JSON.stringify(response_data_json.grid1).如果我使用 JSON.stringify(response_data_json.grid1),我会得到同样的错误。

If i use JSON.parse(response_data_json.grid1) i get:如果我使用 JSON.parse(response_data_json.grid1) 我得到:

Unexpected token ' in JSON at position 1位置 1 处的 JSON 中的意外标记 '

Remove the double quotes in your JSON file:删除 JSON 文件中的双引号:

{
    "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 grid1键有一个string值,你需要它是一个object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM