Home > Software design >  Dart: How to convert json string without quotes to Map
Dart: How to convert json string without quotes to Map

Time:01-27

how to convert json string without quotes to Map.

I tried below code on https://dartpad.dev/ but not working:

import 'dart:convert';

void main() async {
  final String raw = "{data: {name: joy, tags: aa,bb, city: jakarta}}";
  print('Test 1: $raw');
  
  final Map<dynamic, dynamic> result = json.decode(raw);
  print('Test 2: $result');
}

And this is the error for above code:

Test 1: {data: {name: joy, tags: aa,bb, city: jakarta}}
Uncaught Error: FormatException: SyntaxError: Expected property name or '}' in JSON at position 1

And I know this because my json is invalid. How to convert my json string without quotes to json string with quotes?

Actual result is:

{data: {name: joy, tags: aa,bb, city: jakarta}}

Expected result is:

{"data": {"name": "joy", "tags": "aa,bb", "city": "jakarta"}}

CodePudding user response:

Your json is invalid use https://jsonlint.com/ to validate

The json should be

{
    "data": {
        "name": "joy",
        "tags": "aa,bb",
        "city": "Jakarta"
    }
}

DEMO

import 'dart:convert';

void main() async {
  final String raw = "{"  
"   \"data\": {"  
"       \"name\": \"joy\","  
"       \"tags\": \"aa,bb\","  
"       \"city\": \"Jakarta\""  
"   }"  
"}";


  Map<dynamic, dynamic> resultMap = json.decode(raw);
  print('Test 3: $resultMap');
}

CodePudding user response:

What you used is not JSON. In JSON all keys and string values would need quotes. If it were valid JSON you could use

var decodedJson = json.decode(yourString); 
var map = Map.fromIterable(decodedJson, key: (e) => e.keys.first, value: (e) => e.values.first);

but if you would like to convert a string that is like json without quotes you need to write a customized method to do it for you. but in my opinion it won't be clear right if you do this because maybe another strings do not have the same behavior. or i think you should write a method to put quotes before and after the keys and values and after that use json.decode(yourString) if you don't access the string json with quotes.

  • Related