Home > Net >  Covert String to Key-Value Pair or JSON in dart
Covert String to Key-Value Pair or JSON in dart

Time:11-10

I have a String which contains key-value pairs, each key-value pair is surrounded by curly braces {} and separated by comma ,

I know we can use json.decode or jsonDecode but the problem is key or value is not surrounded by quotes "".So json.decode or jsonDecode isn't working for me.

var str = "[{key1: val1, key2: val2}, {key1: val1, key2: val2}, {key1: val1, key2: val2}]";

I want this str like this

[
  {
    "key1":val1,
    "key2":val2
  },
  {
    "key1":val1,
    "key2":val2
  },
  {
    "key1":val1,
    "key2":val2
  }
]

I tried json.decode

{key1: val1, key2: val2}, {key1: val1...
 ^
_ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1405:5)
#1      _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:935:48)
#2      _parseJson (dart:convert-patch/convert_patch.dart:40:10)

I tried json.encode before decode but it is encoding in a wrong way like this

"[{key1: val1, key2: val2}, {key1: val1, key2: val2}, {key1: val1, key2: val2}]"

CodePudding user response:

Okay, this is just a fast horrible hacky solution which can with high probability be improved. But I hope it gets closer to a solution for you:

import 'dart:convert';

void main() {
  var str =
      "[{key1: 0.1, key2: 0.2}, {key1: 0.3, key2: 0.4}, {key1: 0.5, key2: 0.6}]";

  str = str.replaceAll(' ', '').replaceAllMapped(
      RegExp(r'([\{,])([a-zA-Z0-9] )(:)'),
      (match) => '${match.group(1)}"${match.group(2)}"${match.group(3)}');
  
  print(str);
  // [{"key1":0.1,"key2":0.2},{"key1":0.3,"key2":0.4},{"key1":0.5,"key2":0.6}]

  final jsonObject = jsonDecode(str) as List<dynamic>;
  jsonObject.forEach(print);
  // {key1: 0.1, key2: 0.2}
  // {key1: 0.3, key2: 0.4}
  // {key1: 0.5, key2: 0.6}
}
  • Related