skip to Main Content

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"}}

2

Answers


  1. Chosen as BEST ANSWER

    I fix it with below code, refer from this answer: https://stackoverflow.com/a/71025841/21092577

    import 'dart:convert';
    
    void main() async {
      
      String raw = "{data: {name: joy, tags: aa,bb, city: jakarta}}";
      print("Test 0: $raw");
      
      String jsonString = _convertToJsonStringQuotes(raw: raw);
      print("Test 1: $jsonString");
      
      final Map<dynamic, dynamic> result = json.decode(jsonString);
      print('Test 2: $result');
      
    }
    
    
    String _convertToJsonStringQuotes({required String raw}) {
        String jsonString = raw;
    
        /// add quotes to json string
        jsonString = jsonString.replaceAll('{', '{"');
        jsonString = jsonString.replaceAll(': ', '": "');
        jsonString = jsonString.replaceAll(', ', '", "');
        jsonString = jsonString.replaceAll('}', '"}');
    
        /// remove quotes on object json string
        jsonString = jsonString.replaceAll('"{"', '{"');
        jsonString = jsonString.replaceAll('"}"', '"}');
    
        /// remove quotes on array json string
        jsonString = jsonString.replaceAll('"[{', '[{');
        jsonString = jsonString.replaceAll('}]"', '}]');
    
        return jsonString;
      }
    
    

  2. 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');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search