0

How to parse the json which contains array of array values using flutter. I know that this json format is not a valid but unfortunately I need to parse it.

   {
   ModuleEId: [
   [
   "Test Equipment - R&D",
   "GPU_0001_180 KVA Dual AC 28.5V DC"
   ],
   [
   "Test Equipment - Electronics",
   "GPU_0004_180 KVA Dual AC 28.5 V DC"
   ]
   ]
   }
1
  • 1
    Isn't it valid? ((((jsonDecode(string)['ModuleId'] as List)[0] as List)[0]) as String) == "Test Equipment - R&D" Commented Sep 30, 2019 at 11:23

2 Answers 2

2

To parse a json you can use json.decode(jsonString) from package dart:convert. But first, you need to fix the format.

In this case, you could use for example replaceAll method to add the double quotes.

String jsonString = "/*loaded json*/";
jsonString = jsonString.replaceAll('ModuleEId', '"ModuleEId"');

And then

final parsed = json.decode(jsonString);

Full example: Dartpad

Sign up to request clarification or add additional context in comments.

2 Comments

It works as expected. Thanks. Can You say how to map it to a custom model class.?
@DayaNithi I don't know how should your custom model look like. Maybe this could help: Serializing JSON inside model classes.
0

It is not a valid JSON, but it looks like valid YAML. You can take advantage of it. Use yaml package: https://pub.dev/packages/yaml. Then convert it to JSON.

    String input = """
    {
     ModuleEId:
     [
       [
         "Test Equipment - R&D",
         "GPU_0001_180 KVA Dual AC 28.5V DC"
       ],
       [
         "Test Equipment - Electronics",
         "GPU_0004_180 KVA Dual AC 28.5 V DC"
       ]
     ]
    }
    """;
    var yamlDoc = loadYaml(input);
    final json = jsonEncode(yamlDoc);
    print(((((jsonDecode(json)['ModuleEId'] as List)[0] as List)[0]) as String));

3 Comments

It throws error [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'
Are we talking about same input string? Can you copy paste above code and try? It works on my system :-)
No. Actually I tried in mobile. The above answer works thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.