Dart How To parse JSON With Unique Key, Value Pairs

Viewed 3191

I am parsing a JSON object containing several key value pairs but am not sure how to make objects out of the JSON below. The keys are always different depending on the GET request so I am not able to use json['keyname'] like usual. What kind of function would I need in order to return a list of keys from 'ccwms' and a respective list of values (floats)?

    {
  "ccwms": {
    "frc118": 160.8076758518209,
    "frc1255": 15.257951313413884,
    "frc1296": 11.42077882954301,
    "frc7321": -161.58464745359254
  }
}
3 Answers

After parsing the JSON, you have a normal Dart Map with string keys and some values. You can iterate maps in several ways, for example:

for (var key in map.keys) { doSomething(key, map[key]); }

for (var entry in map.entries) { doSomething(entry.key, entry.value); }

map.forEach(doSomething);

(Map.keys, Map.entries, Map.forEach). I'm sure there are more ways to access all the keys and values.

What you do with the keys and values is up to you, it's just a map.

Minimal Dart program to convert a json string:

import 'dart:convert';


main() {
  String source = """{"X":"RRRR","Y":"SSSS","ccwms": {
    "frc118": 160.8076758518209,
    "frc1255": 15.257951313413884,
    "frc1296": 11.42077882954301,
    "frc7321": -161.58464745359254
  }}""";
  dynamic target = JsonDecoder().convert(source);
  print ( source.toString());
}

Are these keys random ? I think keys have to be predefined set, because json is a serialization for already existed object and the object structure can not be random hope I understand correctly

should be a comment but I can not add comments right now.

Related