打印给定JSON(NoSQL)中所有记录的特定字段的值

时间:2019-02-22 15:08:33

标签: json firebase-realtime-database dart flutter

我对flutter和NoSQL还是陌生的。我创建了一个程序,该程序将从firebase中获取数据。我得到的输出是:

{
    "League1": {
        "LeagueName": "League1",
        "SubLeagueName": [
            "SubLeague1",
            "SubLeague2",
            "SubLeague3"
        ]
    },
    "League3": {
        "LeagueName": "League2",
        "SubLeagueName": [
            "SubLeague1",
            "SubLeague2",
            "SubLeague3"
        ]
    } }

我使用了put语句,并且League1,League3是主键。现在,我想创建一个显示所有记录的LeagueName的表。该怎么做?

2 个答案:

答案 0 :(得分:1)

此问题可以通过以下方法解决: 1)将动态输出转换为Map,即

响应为地图

2)遍历此映射的所有键。 3)使用每个记录的每个键查询Map,然后查询每个记录的“ LeagueName”。

for (var i in responseMap.keys){
        leagueNameArray.add(responseMap[i]["LeagueName"]);
      }

答案 1 :(得分:0)

这是另一种方法:

import 'dart:convert';

import 'package:queries/collections.dart';

void main() {
  var dict = Dictionary.fromMap(jsonDecode(_input));
  var query = dict.select((kv) => kv.value["LeagueName"]);
  print(query.toList());
}

var _input = '''
{
    "League1": {
        "LeagueName": "League1",
        "SubLeagueName": [
            "SubLeague1",
            "SubLeague2",
            "SubLeague3"
        ]
    },
    "League3": {
        "LeagueName": "League2",
        "SubLeagueName": [
            "SubLeague1",
            "SubLeague2",
            "SubLeague3"
        ]
    } }''';

结果:

[League1, League2]

P.S。
当Dart支持pipeline运算符时,解决方案可能类似于以下代码:

var list = jsonDecode(_input) as Map
  -> keyValuePairs
  -> select((kv) => kv.value["LeagueName"])
  -> toList;

当Dart支持扩展方法时,解决方案可能类似于以下代码:

var list = mapIterator(jsonDecode(_input))
  .select((kv) => kv.value["LeagueName"])
  .toList();