0

I'm using Flutter and I have a JSON like below:

var json = {
  "key1": {"key": [1,2,3]},
  "key2": {"key": [4,5,7]},
  "key3": {"key": [8,9,10]},
}

I know that, for example, I can retrieve {"key": [4,5,7]} just by calling json["key2"].

But i'm asking, is it possible to retrieve it by using its index position, just like json[1]?

1
  • @someuser Actually "key1", "key2" etc, are sample key names for this example. In reality, the "key1", "key2" etc, are unique id values. Commented Dec 1, 2020 at 16:35

2 Answers 2

1

Yes, change your json to:

{
  "values": [
    {
      "key": [1,2,3]
    },
    {
      "key": [4,5,7]
    },
    {
      "key": [8,9,10]
    }
  ]
}

And access it like: parsedJson["values"][0]

In case you don't want to change your data structure, you can still do it like:

import 'dart:core';

void main() {
  var json = {
  "key1": {"key": [1,2,3]},
  "key2": {"key": [4,5,7]},
  "key3": {"key": [8,9,10]},
  };
  
  List<Map<String, List<int>>> jsonObjects = [];
  
  for (final name in json.keys) {
    final value = json[name];
    print('$value');
    jsonObjects.add(value);
  }
  
  print('$jsonObjects');
  
  print('Second object: ${jsonObjects[1]}');
}

You can try this at https://dartpad.dev

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

5 Comments

Thank you for your answer, I'm getting these data from firebase, so it would be much better if I didn't have to restructure my data, in order to use the solution you recommended.
Ok, in that case, you must make an array of your "key" object and append every key to it, then you are good to go with accessing them by using index :D
That's a great idea. If you want, edit your answer above and include this solution too, so I can accept your answer. Thank you very much!
Thank you, I will include it now
I have updated my answer, you can try this solution on Dartpad too :D
0

A pretty simple answer to this question is

final Map json = {
    "key1": {"key": [1,2,3]},
    "key2": {"key": [4,5,7]},
    "key3": {"key": [8,9,10]},
  };
  
final firstEntry = json.entries.toList()[1].value;
print(firstEntry);

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.