How can I access a value from a list of maps containing a list in Dart? - list

I'm attempting to extract a value from list contained in a list of maps, but am
getting the following error: The operator '[]' isn't defined for the type 'Object'
From the following list, I'd like to access a value such as 'Pizza':
List<Map<String,Object>> questions = [
{
'question': 'What is your favorite food',
'answers': [
'Pizza',
'Tacos',
'Sushi',
],
},
];
When I try to print an answer within the list of answers, it doesn't work:
// Does not work
// The operator '[]' isn't defined for the type 'Object'
print(questions[0]['answers'][0]);
I'm able to save the answers list into a variable to of type list then print a specific list item:
// Works
List answerList = questions[0]['answers'];
print(answerList[0]);
Why doesn't the first way work, and how can I get this to work with one command?

Rather than returning an Object return a dynamic as it has an operator []
List<Map<String, dynamic>> questions = [
{
'question': 'What is your favorite food',
'answers': [
'Pizza',
'Tacos',
'Sushi',
],
},
];

Related

How to make postman assertion on an array

"thing": [
{
"id": 1,
}
]
How do I assert that thing is an array with an object that contains ID
I tried
expect(response.thing).to.deep.include('id');
But that doesn't work
If you want to check:
the array contains String id
pm.expect(JSON.stringify(response.thing)).to.deep.include('id');
a nested object has key id
pm.expect(response.thing[0]).to.have.keys('id');

Access a list item stored in key value pair inside a list of map

I am using flutter/dart and I have run into following problem.
I have a list of map like this.
var questions = [
{
'questionText': 'What\'s your favorite color?',
'answer': ['Black', 'Red', 'Green', 'White']
},
{
'questionText': 'What\'s your favorite animal?',
'answer': ['Deer', 'Tiger', 'Lion', 'Bear']
},
{
'questionText': 'What\'s your favorite movie?',
'answer': ['Die Hard', 'Due Date', 'Deep Rising', 'Dead or Alive']
},
];
Now suppose I need to get the string Tiger from this list. How do I do that? Dart is seeing this as List<Map<String, Object>> questions
Maybe a more portable way with a function:
String getAnswer(int question, int answer) {
return (questions[question]['answer'] as List<String>)[answer];
}
// Get 'Tiger'
String a = getAnswer(1, 1);
You can convert object in list in following way and then use index to get any value.
var p = questions[1]['answer'] as List<String>;
print(p[1]);

Check if inner lists contain some string value in Flutter

I have searched a lot. But couldn't get what I am looking for.
I have a list with inner lists as its objects
final posts = [ ["My First Post, "myPostId"], ["My SecondPost, "myPostId2"]..... ];
So, I want to check if the list contains the word First.
It is working with 1D lists like
posts = ["My First Post", "My Second Post"];
posts.where((p)=>p.contain("First")....
//gives the correct result
But what's the way to get from the inner lists.
Actual Code
final suggestion = query.isEmpty?courseNameList:courseNameList
.where((test)=>test.contains(query.toLowerCase())).toList();
Thanks in advance!
Hello check this solution if it is ok:
final posts = [
["My First Post", "myPostId"],
["My SecondPost", "myPostId2"],
];
void main() {
List suggestions = List();
posts.forEach((postList){
if(postList[0].contains("First"))
suggestions.add(postList);
});
suggestions.forEach((sugg)=>print("Found ID: ${sugg[1]}"));
}
void main() {
final result = posts.any((e) => e.any((e) => e.contains('First')));
print(result);
}
final posts = [
["My First Post", "myPostId"],
["My SecondPost", "myPostId2"]
];

Writing JSON with dict properties to Google Cloud Datastore

Using Apache Beam(Python 2.7 SDK) I am trying to write JSON files as entities into Google Cloud Datastore.
Sample JSON:
{
"CustId": "005056B81111",
"Name": "John Smith",
"Phone": "827188111",
"Email": "john#xxx.com",
"addresses": [
{"type": "Billing", "streetAddress": "Street 7", "city": "Malmo", "postalCode": "CR0 4UZ"},
{"type": "Shipping", "streetAddress": "Street 6", "city": "Stockholm", "postalCode": "YYT IKO"}
]
}
I have written a Apache Beam pipeline with mainly 3 steps,
beam.io.ReadFromText(input_file_path)
beam.ParDo(CreateEntities())
WriteToDatastore(PROJECT)
In step 2, I am converting JSON object(dict) into an entity,
class CreateEntities(beam.DoFn):
def process(self, element):
element = element.encode('ascii','ignore')
element = json.loads(element)
Id = element.pop('CustId')
entity = entity_pb2.Entity()
datastore_helper.add_key_path(entity.key, 'CustomerDF', Id)
datastore_helper.add_properties(entity, element)
return [entity]
This works fine for basic properties. However since address is a dict object itself it fails.
I have read a similar post.
However did not get the exact code to convert dict -> entity
Tried below to set address element as entity but does not work,
element['addresses'] = entity_pb2.Entity()
Other References:
https://www.the-swamp.info/blog/uploading-data-cloud-datastore-using-dataflow/
https://gcloud-python.readthedocs.io/en/latest/datastore/entities.html
Are you trying to store this as a repeated structured property?
ndb.StructuredPropertys appear in dataflow with the keys flattened, and for repeated structured properties, each individual property within the structured property object becomes an array. So I think you would need to write it like this:
datastore_helper.add_properties(entity, {
...
"addresses.type": ["Billing", "Shipping"],
"addresses.streetAddress": ["Street 7", "Street 6"],
"addresses.city": ["Malmo", "Stockholm"],
"addresses.postalCode": ["CR0 4UZ", "YYT IKO"],
})
Alternatively, if youre trying to save this as a ndb.JsonProperty, you can do this:
datastore_helper.add_properties(entity, {
...
"addresses": json.dumps(element['addresses']),
})
I know this is an old question, but I had a similar issue (although Python 3.6 and NDB) and wrote a function to convert all dicts inside a dict into Entity. This uses recursion to go through all nodes converting as necessary:
def dict_to_entity(data):
# the data can be a dict or a list, and they are iterated over differently
# also create a new object to store the child objects
if type(data) == dict:
childiterator = data.items()
new_data = {}
elif type(data) == list:
childiterator = enumerate(data)
new_data = []
else:
return
for i, child in childiterator:
# if the child is a dict or a list, continue drilling...
if type(child) in [dict, list]:
new_child = dict_to_entity(child)
else:
new_child = child
# add the child data to the new object
if type(data) == dict:
new_data[i] = new_child
else:
new_data.append(new_child)
# convert the new object to Entity if needed
if type(data) == dict:
child_entity = datastore.Entity()
child_entity.update(new_data)
return child_entity
else:
return new_data

groovy: create a list of values with all strings

I am trying to iterate through a map and create a new map value. The below is the input
def map = [[name: 'hello', email: ['on', 'off'] ], [ name: 'bye', email: ['abc', 'xyz']]]
I want the resulting data to be like:
[hello: ['on', 'off'], bye: ['abc', 'xyz']]
The code I have right now -
result = [:]
map.each { key ->
result[random] = key.email.each {random ->
"$random"
}
}
return result
The above code returns
[hello: [on, off], bye: [abc, xyz]]
As you can see from above, the quotes from on, off and abc, xyz have disappeared, which is causing problems for me when i am trying to do checks on the list value [on, off]
It should not matter. If you see the result in Groovy console, they are still String.
Below should be sufficient:
map.collectEntries {
[ it.name, it.email ]
}
If you still need the single quotes to create a GString instead of a String, then below tweak would be required:
map.collectEntries {
[ it.name, it.email.collect { "'$it'" } ]
}
I personally do not see any reasoning behind doing the later way. BTW, map is not a Map, it is a List, you can rename it to avoid unnecessary confusions.
You could convert it to a json object and then everything will have quotes
This does it. There should/may be a groovier way though.
def listOfMaps = [[name: 'hello', email: ['on', 'off'] ], [ name: 'bye', email: ['abc', 'xyz']]]
def result = [:]
listOfMaps.each { map ->
def list = map.collect { k, v ->
v
}
result[list[0]] = ["'${list[1][0]}'", "'${list[1][1]}'"]
}
println result