0

I have a very dynamic json object. Example below

//sometime like this
{
    "message": {
        "aaa": [
            "This is aaa"
        ],
        "bbb": [
            "This is bbb"
        ],
        "ccc": [
            "This is ccc",
            "Maybe ddd"
        ]
    }
}
//sometime like this
{
    "message": {
        "fff": [
            "This is fff"
        ],
    }
}
//and sometime like this
{
    "message": "This is a message"
}

I wish to extract any String inside array and turn it into an array of String. Expected result below

//expected result 1
[
    "This is aaa",
    "This is bbb",
    "This is ccc",
    "Maybe ddd"
]
//expected result 2
[
    "This is fff"
]
//expected result 3
[
    "This is a message"
]
5
  • You want to grab strings from any object in which strings are present as keys of map. right? Commented Jul 5, 2021 at 4:22
  • @AayushShah yup, something like that Commented Jul 5, 2021 at 4:24
  • so can you give some more test cases? Commented Jul 5, 2021 at 4:28
  • @AayushShah I already listed 3 example situation might facing when "dynamic" json came in Commented Jul 5, 2021 at 4:33
  • Yup,I tried to go through the main map variable in while loop and I'll check every time that the map's key's variable type is Map or not. If It is map then I can grab it's all key values by [...?mapVar['message']?.keys]; and can append to a universal list. then I will change that map variable to its keys. like mapVar = mapVar.keys then I will again go through this variable in while loop till I get empty or single element like you stated in test case 3. but there is a problem that I cannot type cast a single variable from map to list of strings so that I cannot check the condition in Loop Commented Jul 5, 2021 at 4:40

1 Answer 1

2

Something like this?

Iterable<String> getStrings(dynamic object) sync* {
  if (object is Iterable) {
    for (final value in object) {
      yield* getStrings(value);
    }
  } else if (object is Map) {
    yield* getStrings(object.values);
  } else if (object is String) {
    yield object;
  } else {
    // ignore?
  }
}

void main() {
  final test1 = {
    "message": {
      "aaa": ["This is aaa"],
      "bbb": ["This is bbb"],
      "ccc": ["This is ccc", "Maybe ddd"]
    }
  };
  final test2 = {
    "message": {
      "fff": ["This is fff"],
    }
  };
  final test3 = {"message": "This is a message"};

  print([...getStrings(test1)]);
  // [This is aaa, This is bbb, This is ccc, Maybe ddd]
  print([...getStrings(test2)]);
  // [This is fff]
  print([...getStrings(test3)]);
  // [This is a message]
}
Sign up to request clarification or add additional context in comments.

Comments

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.