Python get a value in JSON array - arrays

In Python 3-x, consider you have an array in JSON syntax:
members = '''[
{
"name" : "Amber",
"age" : 5
},
{
"name" : "Becky",
"age" : 4
}
]'''
How do you get the value for age where the name is Amber? (The answer should be 5).

variable members look like a string so first change string to json object and search what you want.
members = '''[
{
"name" : "Amber",
"age" : 5
},
{
"name" : "Becky",
"age" : 4
}
]'''
import json
obj = json.loads(members) #Changing string to json
for some_variable in obj:
if some_variable['name'] == 'Amber':
print (some_variable['age']) # will print 5

Related

[MongoDB]How to find an object from array?

I'm trying to query single object from an array of objects.
The array looks like this.
db.getCollection('user').getIndexes();
[
{
"v" : 1,
"key" : {
"_id" : 1
}
},
{
"v" : 1,
"key" : {
"name" : 1
}
},
{
"v" : 1,
"key" : {
"admin" : 1
}
}
]
Don't know how to find an element with "_id" property name in "key" object.
db.getCollection('user').getIndexes().[some sorting query];
{
"v" : 1,
"key" : {
"_id" : 1
}
}
Does anyone have an idea? Thank you.
The getIndexes helper in the mongo shell accepts a filter as an argument, like:
db.getCollection("user").getIndexes({"key._id":{$exists:true}})
From a driver, you can run the listIndexes command similarly:
database.runCommand({listIndexes:"user", "key._id":{$exists:true}})

Arabic text in swift

i have array of objects like this
"sub-specialty" : [
{
"id" : 1,
"title" : "Adult Physiotherapy",
"ar_title" : "علاج طبيعي بالغين",
"name" : "علاج طبيعي بالغين"
},
{
"id" : 2,
"title" : "Pediatric Physiotherapy",
"ar_title" : "علاج طبيعي اطفال",
"name" : "علاج طبيعي اطفال"
},
{
"id" : 3,
"title" : "Sport Injuries",
"ar_title" : "اصابات ملاعب",
"name" : "اصابات ملاعب"
},
{
"id" : 4,
"title" : "Rehabilitation",
"ar_title" : "تأهيل",
"name" : "تأهيل"
}
]
when i use map to grab name only like this
let sub = sub-specialty.map({($0.name ?? "")}).joined(separator: ", ") ?? ""
i got rubbish characters or text is flipped please see the attached image
enter image description here
You need to get the text as String and set wherever you want to set. It will work fine. I have worked with multi languages and this work for me.

Append array element to String(Swift)

I am trying to make an array of random numbers for an ID for 25 people so I figured that would be the easiest way would use a array map but is there a way to take each element and attach it to an "email" in the dictionary key.
class ClassRosterModel {
var randomArray = (1...25).map{_ in arc4random()}
var studentsRoster = [Dictionary<String, String>] ()
init () {
studentsRoster.append(["name": "Kacz, Alex", "major" : "SE", "email" : ".join(randomArray[0])#email.edu", "currentTerm" : "Spring", "numberOfCredits" : "" ])
studentsRoster.append(["name": "O'Rore, Ryan", "major" : "SE", "email" : ".join(randomArray[0]#email.edu", "currentTerm" : "Fall", "numberOfCredits" : "" ])
}
}
From what I am understanding, you want to put a value inside a string. You can use \().
Example:
let value = 101
let email = "myname\(value)#email.com"
print(email)
The console result will be:
myname101#email.com
Just use your randomArray instead of value. And save the email inside your dictionary.
studentsRoster.append(["name": "Kacz, Alex", "major" : "SE", "email" : ".join\(randomArray[0])#email.edu", "currentTerm" : "Spring", "numberOfCredits" : "" ])
studentsRoster.append(["name": "O'Rore, Ryan", "major" : "SE", "email" : ".join\(randomArray[0])#email.edu", "currentTerm" : "Fall", "numberOfCredits" : "" ])

using json object with lots of properties instead of arrays

instead of an array:
var arrayExample = {
"lotsOfStuff" : [
{"id" : "th1", "name" : "thing1", "type": "thing", "moo":"a"},
{"id" : "th2", "name" : "thing2", "type": "thing", "moo":"z"},
{"id" : "th3", "name" : "aDifferentThing3", "type": "differentThing", "moo":"m"}
]
}
Use lots of properties:
var propertyExample = {
"lotsOfStuff" : {
"id1" : {"name" : "thing1", "type" : "thing", "moo" : "a" },
"id2" : {"name" : "thing2", "type" : "thing", "moo" : "z" },
"id3" : {"name" : "aDifferentThing3", "type" : "differentThing", "moo" : "m" }
}
}
can still iterate through them
for(var idx in arrayExample.lotsOfStuff) {
var thing = lotsOfStuff[idx];
var id = thing.id;
...
}
and
for(var id in propertyExample) {
var thing = lotsOfStuff[id];
...
}
but you have the bonus of a lookup by id at the expense of the lookup by index position
Any problems with using this array alternative??
what about performance with lots of elements??
If the order of the elements matters, use an array.
If you need to look up by ID, use an object.
If you need to do both, create both an array and an object whose elements point to the same objects.
Accessing object properties is probably slower than accessing array elements, because it requires hashing instead of simple indexing. But if you need to look up by ID in an array, that will require a linear search, which is much slower than hashing if there are lots of elements. The performance of objects should not be impacted significantly by the number of elements.

update nth document in a nested array document in mongodb

I need to update a document in an array inside another document in Mongo DB
{
"_id" : ObjectId("51cff693d342704b5047e6d8"),
"author" : "test",
"body" : "sdfkj dsfhk asdfjad ",
"comments" : [
{
"author" : "test",
"body" : "sdfkjdj\r\nasdjgkfdfj",
"email" : "test#tes.com"
},
{
"author" : "hola",
"body" : "sdfl\r\nhola \r\nwork here"
}
],
"date" : ISODate("2013-06-30T09:12:51.629Z"),
"permalink" : "jaiho",
"tags" : [
"jaiho"
],
"title" : "JAiHo"
}
Q1) Update email of 0th element of comments array
db.posts.update({"permalink" : "haha"},{$set:{"comments.0.email":1}})
This doesn't throw any exception but doesn't update anything as well
Q2) Add a field on nth element of comments array number_likes
db.posts.update({"permalink" : "haha"},{$inc:{"comments.0.num_likes":1}})
Doesn't work either.
Am I missing something here?
Q1: If you update with permalink 'jaiho' instead of 'haha', it most certainly updates the email;
> db.posts.update({"permalink" : "jaiho"},{$set:{"comments.0.email":1}})
> db.posts.find()
..., "email" : 1 },...
Q2: Same goes for this include;
> db.posts.update({"permalink" : "jaiho"},{$inc:{"comments.0.num_likes":1}})
> db.posts.find()
..., "num_likes" : 1 },...
If you are trying to do it dynamically in Node JS following should work.
i = 0;
selector = {};
operator = {};
selector['comments.' + i + '.email'] = 1; // {'comments.0.num_likes' : 1}
operator['$inc'] = selector; // {'$inc' : {'comments.0.num_likes' : 1} }
db.posts.update({'permalink' : 'xyz'}, operator);

Resources