【问题标题】:Flutter Parsing Nested Array Json value using conditional statementsFlutter 使用条件语句解析嵌套数组 Json 值
【发布时间】:2022-01-15 20:52:35
【问题描述】:

我有一个 csv 表,我将其转换为 json,并希望根据条件语句在 Flutter 中解析此 json。

例如,第一个条件是类型是否为行星,如果名称与提供的值匹配,则在列表视图中显示其余详细信息,如字符、颜色和距离。

输入只是类型和名称,因此我需要解析 json 并提取正确的数据。

我可以为每种类型设置 6 个单独的 json,但这对我来说似乎不是一个好主意。

关于如何使用条件语句或将此 json 转换为不同格式的任何建议,以便我可以使用 Flutter 中的索引或元素进行解析。

[
  {
    "Type": "Planet",
    "Name": "Jupiter",
    "Charcs": "Largest",
    "Color": "blue",
    "distance": "near"
  },
  {
    "Type": "Planet",
    "Name": "Earth",
    "Charcs": "Inhabited",
    "Color": "green",
    "distance": "nearby"
  },
  {
    "Type": "Planet",
    "Name": "Mars",
    "Charcs": "Red Planet",
    "Color": "red",
    "distance": "very near"
  },
  {
    "Type": "Star",
    "Name": "Polaris",
    "Charcs": "abcddw",
    "Color": "casc",
    "distance": "far"
  },
  {
    "Type": "Star",
    "Name": "Sirius",
    "Charcs": "qwqwd",
    "Color": "asfaf",
    "distance": "very far"
  },
  {
    "Type": "Star",
    "Name": "Betelgeuse",
    "Charcs": "qwdwqeq",
    "Color": "asfasfa",
    "distance": "far far away"
  }
]

【问题讨论】:

    标签: json flutter dart


    【解决方案1】:

    因为这是一个数组,您可以使用一个循环将每个项目过滤成一个单独的 JSON 键。

    var array = [
      {
        "Type": "Planet",
        "Name": "Jupiter",
        "Charcs": "Largest",
        "Color": "blue",
        "distance": "near"
      },
      {
        "Type": "Planet",
        "Name": "Earth",
        "Charcs": "Inhabited",
        "Color": "green",
        "distance": "nearby"
      },
      {
        "Type": "Planet",
        "Name": "Mars",
        "Charcs": "Red Planet",
        "Color": "red",
        "distance": "very near"
      },
      {
        "Type": "Star",
        "Name": "Polaris",
        "Charcs": "abcddw",
        "Color": "casc",
        "distance": "far"
      },
      {
        "Type": "Star",
        "Name": "Sirius",
        "Charcs": "qwqwd",
        "Color": "asfaf",
        "distance": "very far"
      },
      {
        "Type": "Star",
        "Name": "Betelgeuse",
        "Charcs": "qwdwqeq",
        "Color": "asfasfa",
        "distance": "far far away"
      }
    ]
    
    var json = {}
    array.forEach(e => {
      json[e.Type] ||= {}
      json[e.Type][e.Name] = {Charcs: e.Charcs,Color: e.Color,distance:e.distance}
    })
    console.log(json)

    上面代码的定义如下:

    1. json[e.Type] ||= {}:如果对象类型不存在,这将创建一个键
    2. json[e.Type][e.Name] = {Charcs: e.Charcs,Color: e.Color,distance:e.distance}:这会将对象的数据放在自己的子键中

    【讨论】:

    • 或者,如果您希望数据是数组而不是 json,只需将 {Charcs: e.Charcs,Color: e.Color,distance:e.distance} 替换为 [e.Charcs,e.Color,e.distance]
    猜你喜欢
    • 1970-01-01
    • 2019-01-24
    • 2015-06-15
    • 2020-09-24
    • 2019-12-30
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多