-1

I'm trying to cut a JSON String to the values after an insert key in Flutter/Dart.

For example I have this JSON String:

  [{"insert":"Test12\n"},{"insert":"Test1","attributes":{"b":true}},{"insert":"\nTest"},{"insert":"\n","attributes":{"block":"quote"}},{"insert":"Test","attributes":{"s":true}},{"insert":"\nTest"},{"insert":"\n","attributes":{"block":"ol"}},{"insert":"Test"},{"insert":"\n","attributes":{"block":"ol"}},{"insert":"Test"},{"insert":"\n","attributes":{"block":"ul"}},{"insert":{"_type":"hr","_inline":false}},{"insert":"\n"},{"insert":"Test","attributes":{"i":true,"u":true,"s":true,"b":true}},{"insert":"\n\n"}]

I want to convert this String to just its values after an insert. So the result would be:

Test12 Test1 Test Test Test Test Test Test

I don't need for example these characters "" , . {} \n

Test stands for different strings.

I played around with some RegEx but I can not get it working. Am I even on the right path with RegEx?

Thanks in advance.

Florian
  • 226
  • 2
  • 11
  • I don't understand your question. You want to get the values that has "insert" key? Or all the values? – sonny Feb 03 '21 at 17:46
  • Would it be only all those "Test" strings that you wrote? What about the "insert": "\n", "insert": "\n\n" and also the object/map: "insert":{"_type":"hr","_inline":false} ? – Robert Sandberg Feb 03 '21 at 18:09

1 Answers1

1

It's json, so you might as well decode it :

var jsonString =  '[{"insert":"Test12\n"},{"insert":"Test1","attributes":{"b":true}},{"insert":"\nTest"},{"insert":"\n","attributes":{"block":"quote"}},{"insert":"Test","attributes":{"s":true}},{"insert":"\nTest"},{"insert":"\n","attributes":{"block":"ol"}},{"insert":"Test"},{"insert":"\n","attributes":{"block":"ol"}},{"insert":"Test"},{"insert":"\n","attributes":{"block":"ul"}},{"insert":{"_type":"hr","_inline":false}},{"insert":"\n"},{"insert":"Test","attributes":{"i":true,"u":true,"s":true,"b":true}},{"insert":"\n\n"}]';
jsonString = jsonString.replaceAll('\n', '\\n');
// jsonDecode() will convert the json to objects of primitive types.
var result = jsonDecode(jsonString) as List<dynamic>;
var inserts = [ for(var map in result) map["insert"]];
for(var insert in inserts)
  print(insert);
MickaelHrndz
  • 3,604
  • 1
  • 13
  • 23
  • If you don't want the \n , then replace `'\\n'` with `''`. To only get strings tied to the "insert" key, paste `if(map["insert"] is String)` before `map["insert"]`. – MickaelHrndz Feb 03 '21 at 20:39