简体   繁体   English

将 json 转换为数组/映射

[英]convert json to array/map

My rest API returns with the following json content:我的 rest API 返回以下 json 内容:

[{
    "key": "apple",
    "value": "green"
},
{
    "key": "banana",
    "value": "yellow"
}]

I am iterating through the list with this code:我正在使用以下代码遍历列表:

this.props.json.map(row => {
    return <RowRender key={id.row} row={row} />
}

It works because the content is displayed but on the web browser's console I can see an error:之所以有效,是因为内容已显示,但在 Web 浏览器的控制台上,我可以看到错误:

map is not a function地图不是函数

I googled for it and I changed my code to this:我用谷歌搜索它并将我的代码更改为:

Array.prototype.slice.call(this.props.json).map(row => {
    return <RowRender key={id.row} row={row} />
}

It works without any error but seems so complicated.它的工作没有任何错误,但看起来很复杂。 Is that the correct way to do this job?这是做这项工作的正确方法吗?


UPDATE更新

What I tried:我试过的:

  • JSON.parse(...).map: Unexpected end of JSON input JSON.parse(...).map: JSON 输入意外结束
  • JSON.parse(JSON.stringify(...)).map(...): data is displayed but I get an error: JSON.parse(...).map is not a function JSON.parse(JSON.stringify(...)).map(...): 数据显示但我收到一个错误:JSON.parse(...).map is not a function
  • Array(...).map: Each child in array or iterator should have a unique key. Array(...).map:数组或迭代器中的每个子元素都应该有一个唯一的键。
let myMap = new Map(Object.entries(this.props.json));

in your code this.props.json is not an array, it's an array-like object and map is an array function.在你的代码中this.props.json不是一个数组,它是一个类似数组的对象,而 map 是一个数组函数。 what your doing to solve this, is converting that array-like object into an array, with .slice()您为解决此问题所做的工作是使用 .slice() 将该类数组对象转换为数组

a more elegant way to do this:一个更优雅的方式来做到这一点:

Array.from(this.props.json).map(row => <RowRender key={id.row} row={row} />)
let jsonMap = JSON.stringify([...map.entries()])
let myMap = new Map(JSON.parse(jsonMap));

You can do it very easily as @Gary mentioned in his answer:正如@Gary 在他的回答中提到的那样,您可以非常轻松地做到这一点:

From Map to JSON (string keys):MapJSON (字符串键):

 const personsJson = `{"1":{"firstName":"Jan","lastName":"Kowalski"},"2":{"firstName":"Justyna","lastName":"Kowalczyk"}}`; const personsObject = JSON.parse(personsJson); const personsMap = new Map(Object.entries(personsObject)); for (const key of personsMap.keys()) { console.log(typeof key) }

But there is one issue about which you have to be careful.但是有一个问题你必须小心。 Key of the map created in that way will always be a STRING .以这种方式创建的地图的键将始终是STRING It will happen, because KEY of JSON object is always a STRING .它会发生,因为 JSON 对象的 KEY 始终是 STRING So if your Map keys should be numbers then first you have parse keys of your object entries.所以如果你的 Map 键应该是数字,那么首先你有对象条目的解析键。

  • From JSON to Map (number keys): :JSONMap (数字键) ::

 const personsJson = `{"1":{"firstName":"Jan","lastName":"Kowalski"},"2":{"firstName":"Justyna","lastName":"Kowalczyk"}}`; const personsObject = JSON.parse(personsJson); const personObjectEntries = Object.entries(personsObject); const personObjectEntriesNumberKeys = personObjectEntries.map(person => { person[0] = parseInt(person[0]); return person; }); const personsMap = new Map(personObjectEntriesNumberKeys); for (const key of personsMap.keys()) { console.log(typeof key) }

There is person[0] because under 0 index there is the key of the objectperson[0]因为在 0 索引下有对象的键

You can copypaste this function: it would take JSON and return a Map of Maps:您可以复制粘贴此函数:它将采用 JSON 并返回一个 Map of Maps:

It works with this JSON:它适用于这个 JSON:

{
   "data":{
      "1":{
         "color":"red",
         "size":"big"
      },
      "2":{
         "color":"red",
         "size":"big"
      },
      "3":{
         "color":"red",
         "size":"big"
      },
      "4":{
         "color":"red",
         "size":"big"
      },
      "5":{
         "color":"red",
         "size":"big"
      }
   }
}
function jsonToMap(jsonString)  {
    var jsonObject = JSON.parse(jsonString);
    var dataObject = jsonObject.data;
    var dataMap = new Map(Object.entries(dataObject));
    var resultMap = new Map();
    for (const key of dataMap.keys())  {
        console.log(key);
        var keyMap = new Map(Object.entries(dataMap.get(key)));
        resultMap.set(key, keyMap);
    }

    console.log("done!");
    return resultMap;
}

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

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