Home > Enterprise >  Dart - Changing Json Map dynamically
Dart - Changing Json Map dynamically

Time:03-05

I need to modify a json (Map<String, dynamic>). Need to update values, add new values, etc. But the problem is: If the new value I'm trying to add (or update), is not of the same type of actual value or String, it throws an Exception......

Is there a way to insert or modify a json with new types of values???

(In C# with newtonsoft json, or in NodeJs, I am able to do it easyly)

This is the code to reproduce the problem:

void main() {
  Map<String, dynamic> _json = {
    'key 1': 'value 1',
    'key 2': 'value 2',
    'key 3': {
      'key 3_1': {
        'key 3_1_1': 'value 3.1.1'
      }
    },
    'key 4': {
      'key 4.1': {
        'key 4.1.1': 'value 4.1.1'
      }
    },
    'key 5': 4,
    'key 6': true
  };
  
  (_json['key 3']['key 3_1'] as Map<String, dynamic>).update('key 3_1_1', (v) => '4'); // <---- this works
  (_json['key 3']['key 3_1'] as Map<String, dynamic>).update('key 3_1_1', (v) => 4); // <--- this does not work
  (_json['key 3']['key 3_1'] as Map<String, dynamic>).putIfAbsent('key 3_1_2', () => 4); // <--- this does not work too
  (_json['key 3']['key 3_1'] as Map<String, dynamic>).putIfAbsent('key 3_1_2', () => {'a': '4'}); // <--- this does not work
  print(_json);
}

CodePudding user response:

I found a way to do it!

Just need to import dart:convert and add this line BEFORE any json operations:

_json = json.decode(json.encode(_json));

I don't know why but converting json inline is different from creating a new json using convert..

CodePudding user response:

The reason is that your original "JSON" map literals are typed. For example, the subexpression

      {
        'key 3_1_1': 'value 3.1.1'
      }

has type Map<String, String> because that's the apparent type of the elements, and there is no context type overriding it (the context type is just dynamic, if anything).

If you wrote the original code as:

Map<String, dynamic> _json = {
    'key 1': 'value 1',
    'key 2': 'value 2',
    'key 3': <String, dynamic>{
      'key 3_1': <String, dynamic>{
        'key 3_1_1': 'value 3.1.1'
      }
    },
    'key 4': <String, dynamic>{
      'key 4.1': <String, dynamic>{
        'key 4.1.1': 'value 4.1.1'
      }
    },
    'key 5': 4,
    'key 6': true
  };

you would get the same effect as JSON-encoding and then decoding (and much more efficiently).

  • Related