'Dart - Changing Json Map dynamically

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);
}


Solution 1:[1]

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..

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GnRSlashSP