Getting items from an api using django - python

I am trying to get the amount value from the available field when I retrieve a blance from Stripe. I have the following response:
{
"available": [
{
"amount": 10302,
"currency": "cad",
"source_types": {
"card": 10302
}
}
],
"livemode": false,
"object": "balance",
"pending": [
{
"amount": 0,
"currency": "cad",
"source_types": {
"card": 0
}
}
]
}
I am trying to get the available amount, so I wrote the following:
available = balance['available']
as a response I am getting the following:
[<StripeObject at 0x110d45a98> JSON: {
"amount": 10302,
"currency": "cad",
"source_types": {
"card": 10302
}
}]
But how can I get access to the 'amount' part?
I tried:
amount = available['amount']
So I am receiving:
TypeError at /en/accounts/profile/
list indices must be integers or slices, not str
as an error.

balance['available'] contains a dictionary ({}) inside of a list ([]). Therefore, the dictionary is stored as the first element of the list, and has to be accessed using available[0]. You can get the value that corresponds to the 'amount' key by typing available[0]['amount'].

Related

Extracting fields from a json file

I am provided with the following json file.
{
"results": [
{
"id": "1234",
"useless_field1": null,
"useless_field2": null,
"data": [
{
"type": "type_1",
"useless_field3": null,
"volumne": "5"
}
]
}
]
}
I would like to extract only the following fields: id, type, volume. I did it in the following way.
def extract(json_response):
return [{
item['id'],
item['data'][0]['type'],
item['data'][0]['volume']
} for item in json_response['results']]
It is possible for the type to be a list. Is my solution efficient? Are there any alternatives of solving such problems?

How can I access and count a value of an attribute of Json file in Python?

I have this json file. It's a report of threat intelligence platform.
{
"data": {
"attributes": {
"authentihash": "a077f952798eb3bc0730c7c4774da7636326cf4b524ed6571b7eaf3d43f0bd9b",
"creation_date": 1387937380,
"crowdsourced_yara_results": [
{
"author": "Florian Roth",
"description": "Malware InstallRex / AntiFW",
"rule_name": "PUP_InstallRex_AntiFWb",
"ruleset_id": "000ca30c43",
"ruleset_name": "crime_antifw_installrex",
"source": "https://github.com/Neo23x0/signature-base"
}
],
"first_submission_date": 1389124248,
"last_analysis_date": 1603898773,
"last_analysis_results": {
"ALYac": {
"category": "undetected",
"engine_name": "ALYac",
"engine_update": "20201028",
"engine_version": "1.1.1.5",
"method": "blacklist",
"result": null
},
"APEX": {
"category": "undetected",
"engine_name": "APEX",
"engine_update": "20201028",
"engine_version": "6.90",
"method": "blacklist",
"result": null
},
"AVG": {
"category": "malicious",
"engine_name": "AVG",
"engine_update": "20201028",
"engine_version": "18.4.3895.0",
"method": "blacklist",
"result": "FileRepMetagen [Malware]"
},
I would count how many antimalware detected the malware as "maliciuous". So
i can access and print the whole list of "last_analysis_results", but i can't access to "category" of each antimalware.
I try with:
for elem in data['data']['attributes']['last_analysis_results']:
but then? thank you :)
Use .values() to get the dictionary values. Then you can access the category element of each dictionary.
sum(r['category'] == 'malicious' for r in data['data']['attributes']['last_analysis_results'].values())
Booleans are treated as 1 and 0 when used arithmetically, so summing the comparisons counts the number of times it's true.

Get field value in MongoDB without parent object name

I'm trying to find a way to retrieve some data on MongoDB trough python scripts
but I got stuck on a situation as follows:
I have to retrieve some data, check a field value and compare with another data (MongoDB Documents).
But the Object's name may vary from each module, see bellow:
Document 1
{
"_id": "001",
"promotion": {
"Avocado": {
"id": "01",
"timestamp": "202005181407",
},
"Banana": {
"id": "02",
"timestamp": "202005181407",
}
},
"product" : {
"id" : "11"
}
Document 2
{
"_id": "002",
"promotion": {
"Grape": {
"id": "02",
"timestamp": "202005181407",
},
"Dragonfruit": {
"id": "02",
"timestamp": "202005181407",
}
},
"product" : {
"id" : "15"
}
}
I'll aways have an Object called promotion but the child's name may vary, sometimes it's an ordered number, sometimes it is not. The field I need the value is the id inside promotion, it will aways have the same name.
So if the document matches the criteria I'll retrieve with python and get the rest of the work done.
PS.: I'm not the one responsible for this kind of Document Structure.
I've already tried these docs, but couldn't get them to work the way I need.
$all
$elemMatch
Try this python pipeline:
[
{
'$addFields': {
'fruits': {
'$objectToArray': '$promotion'
}
}
}, {
'$addFields': {
'FruitIds': '$fruits.v.id'
}
}, {
'$project': {
'_id': 0,
'FruitIds': 1
}
}
]
Output produced:
{FruitIds:["01","02"]},
{FruitIds:["02","02"]}
Is this the desired output?

Troubles with validating nested values

I am looking to add validation to my api endpoint using Marshmallow.
I am running into the problem of how to get this chunk properly validated. The end goal is to make sure impressions is a positive number.
I would greatly appreciate any help or insight you can provide. First time using Marshmallow.
Sample Json:
{
"mode": [
{
"type": "String",
"values": {
"visits": 1000,
"budget": 400
},
"active": true
}
]
}
Sample code attempting to validate
class ValidateValues(BaseSchema):
visits = fields.Int(allow_none=True, validate=[validate.Range(min=0, error="Value must be greater than 0")])
budget = fields.Int(allow_none=True, validate=[validate.Range(min=0, error="Value must be greater than 0")])
class ModeSchema(BaseSchema):
type = fields.String(required=True)
active = fields.Boolean(required=True)
values = fields.Nested(ValidateValues)
class JsonSchema(BaseSchema):
mode = fields.List(fields.Dict(fields.Nested(ModeSchema, many=True)))
Current result
{
"mode": {
"0": {
"type": {
"key": [
"Invalid type."
]
},
"values": {
"key": [
"Invalid type."
]
},
"active": {
"key": [
"Invalid type."
]
}
}
}
}
You're just using a list of Nested fields. No need for Dict, here.
And no need for many=True since you're putting the Nested field in a List field.
Try this:
class JsonSchema(BaseSchema):
mode = fields.List(fields.Nested(ModeSchema))

Parse json response in python

The workplace api returns a json response:
{
"name": "AA",
"owner": {
"name": "ser1",
"id": "1234"
},
"id": "567",
"admins": {
"data": [
{
"name": "codez",
"id": "457"
},
],
"paging": {
"cursors": {
"before": "qwrqwreqreqr",
"after": "teyryryryr"
}
}
}
I access the json response in python using the below for loop:
for item in feed:
row = [item["name"],item["id"], item["email"], item["privacy"],item["updated_time"],item["admins"]["data"]["name"]]
I get the error "list indices must be integers or slices, not list". When I remove the item["admins"]["data"]["name"], I don't get the error message.
Any suggestions would be appreciated !!
You need to access list. The data node contains a list so you need to access index 0 then access the key value pair.
for item in feed:
row = [item["name"],item["id"], item["email"], item["privacy"],item["updated_time"],item["admins"]["data"][0]["name"]]
data maps to a list with size one so you could do item["admins"]["data"][0]["name"]
Although this could be done much easier with row = item.values()

Categories

Resources