Accessing values from json in Pylons - python

In my controller I'm getting a json string (called c.order_history which looks like:
[
{
"status": [
{
"status": "created",
"timestamp": "2012-04-06 00:14:10"
},
{
"status": "authed",
"timestamp": "2012-04-06 00:14:17"
}
],
"product_info": [
{
"id": 3,
"quantity": 1,
"created": "2012-04-06 00:14:10",
"image_id": 13341
},
{
"id": 2,
"quantity": 1,
"created": "2012-04-06 00:14:10",
"image_id": 13323
},
{
"id": 1,
"quantity": 1,
"created": "2012-04-06 00:14:10",
"image_id": 13322
}
],
"shipping_charge": "0.00",
"order_number": "0723094747433",
"shipping_address": {
"country_code": null,
"extended_address": "Unit Z",
"locality": "Las Vagas",
"company": null,
"phone": null,
"postal_code": "31415",
"full_name": "Boris Karloff",
"nickname": null,
"region": "NV",
"street_address": "123 Random Way"
},
"subtotal": "59.00"
}
]
I'm passing it through json.loads(order_history) to turn it into a dict, and then trying to extract each key so I can then get the subsequent key/values within them like:
c.product_info = [{'product_info' : product_info} for product_info in c.order_history]
Which outputs the entire json string, but it's just named product_info now. Can someone steer me in the right direction on how I can access say, the timestamp value, product_info[0]['image_id'] and shipping_address values, etc.?

It looks like c.order_history will be a list of dictionaries, to just grab the product_info key from each of these dictionaries in a list comprehension you would do the following:
[{'product_info': order['product_info']} for order in c.order_history]

Related

accessing json data in python and fast api

test_data = {
"transactions": [{
"id": 5494,
"specific_wallet_id": 2079,
"evaluation_process_transaction_id": 5229,
"transaction_type": "Earn",
"points": 9,
"created_at": "2022-09-20T16:14:19.000+05:30",
"updated_at": "2022-09-20T16:14:19.000+05:30",
"custom_wallet_transaction_id": "null",
"order_meta_data": {},
"points_validity": "2023-09-20T00:00:00.000+05:30",
"points_status": "Active",
"transaction_amount": 450.0,
"transaction_at": "2022-09-20T16:14:18.000+05:30",
"tnx_status": "Successful",
"current_points": 9,
"programme_id": 4,
"customer_id": 1,
"reason_code": "Earn",
"channel": "app",
"order_id": "1",
"transaction_references": "null",
"points_value": 9.0,
"issuer": {
"id": 1,
"name": "oo",
"code": "oo",
"image_url": "null"
},
"partner": null
},
{
"id": 5486,
"specific_wallet_id": 2079,
"evaluation_process_transaction_id": 5221,
"transaction_type": "Earn",
"points": 9,
"created_at": "2022-09-20T15:46:15.000+05:30",
"updated_at": "2022-09-20T15:46:15.000+05:30",
"custom_wallet_transaction_id": "null",
"order_meta_data": {},
"points_validity": "2023-09-20T00:00:00.000+05:30",
"points_status": "Active",
"transaction_amount": 450.0,
"transaction_at": "2022-09-20T15:46:14.000+05:30",
"tnx_status": "Successful",
"current_points": 9,
"programme_id": 4,
"customer_id": 2189,
"reason_code": "Earn",
"channel": "app",
"order_id": "uuu",
"transaction_references": "null",
"points_value": 9.0,
"issuer": {
"id": 1,
"name": "oo",
"code": "ooo",
"image_url": "null"
},
"partner": {
"id": 1,
"name": "qq",
"code": "qq",
"image_url": "https://d157777v0iph40..net///offers/avis.jpg"
}
}
],
"success": "true",
"error": "null"
}
results=[]
results.extend(
[
AllTransaction(
issuer_id=Config.evaluation_issuer_id,
issuer_name="",
issuer_logo="",
wallet_id=o["specific_wallet_id"],
partner=o["partner"],
points=o["points"],
points_value_in_currency=(
o["points"] * 1
),
transaction_at=o["transaction_at"],
transaction_id=o["id"],
transaction_type=o["transaction_type"],
transaction_meta={
"order_id": o["order_id"],
"channel": o["channel"],
"order_meta_data": o["order_meta_data"],
},
transaction_name=o["transaction_type"],
)
for o in test_data["transactions"]
]
)
return TransactionResponse(results=results)
model code
class TransactionDetailsPartner(BaseModel):
partner: Optional[dict] =None
class TransactionDetails(BaseModel):
points: int
points_value_in_currency: float
transaction_id: int
transaction_at: datetime
transaction_type: str
transaction_meta: Optional[dict]
transaction_name: Optional[TransactionType]
class TransactionDetailsIssuer(BaseModel):
issuer_id: int
issuer_name: str
issuer_logo: str
wallet_id: int
class AllTransaction(TransactionDetails, TransactionDetailsIssuer, TransactionDetailsPartner):
pass
**this is my main method and here my partnerdata is null in one entry at test_data
and in pydantic model i made as optional but still it throwing error if i pass null data how to resolve this **
how to access this partner key even it is null and at model or api level is ok.
thanks in advance
The code that you gave is not valid Python, null is a valid JSON value but in Python it has to be None.
Try to load the string as JSON and then parse it to a Pydantic model.

Elasticsearch DSL, filter list of objects with in list of values

my data looks like this:
[
{
"id": "00f0bbe514dcaf262c8a",
"status": "CL",
"type": "opportunity",
"locations": [
{
"name": "New York, USA",
"lat": 99.0853,
"lng": 99.7818,
"id": "456",
"type": "CI"
},
{
"name": "Boston, USA",
"lat": 80.0853,
"lng": 80.7818,
"id": "555",
"type": "CI"
},
{
"name": "London, UK",
"lat": 10.0853,
"lng": 10.7818,
"id": "999",
"type": "CI"
}
]
},
{
"id": "sadl9asod01",
"status": "CL",
"type": "opportunity",
"locations": [
{
"name": "Boston, USA",
"lat": 80.0853,
"lng": 80.7818,
"id": "555",
"type": "CI"
},
]
},
{
"id": "13094ulk",
"status": "CL",
"type": "project", # has right location but not type
"locations": [
{
"name": "Boston, USA",
"lat": 80.0853,
"lng": 80.7818,
"id": "555",
"type": "CI"
},
]
}
]
I want to build a query that the type must be opportunity:
type_q = ElasticQ('bool', must=[ElasticQ('match', type='opportunity')])
query = self.index.search().query(type_q)
I know how to build an "in" query with the dsl, for example:
excluded_ids = self._excluded_jobs() # list
query = query.exclude('terms', id=excluded_ids)
but, how can I add to the query what in SQL I would do like this:
WHERE type='opportunity'
AND
location.id in (1, 2, 3)
location represents here object inside the locations array of the doc
Something like:
type_q = ElasticQ('bool', must=[
ElasticQ('match', type='opportunity'),
ElasticQ('terms', id=excluded_ids),
])
Or, if you actually wanted to exclude those IDs:
type_q = ElasticQ('bool',
must=[ElasticQ('match', type='opportunity')]
must_not=[ElasticQ('terms', id=excluded_ids)]
)

How do I iterate over 2 JSON lists (mix dict and list), match specific values and print another value

I have 2 separate JSON-Lists (with dicts) in it.
My goal is, that I want to iterate over list2 "currentUser", grab the values, search those values in list1, and as output print the value of "firstName"
e.g.
liste2: "currentUser": 123,
liste1: "id": "123", --> "firstName": "Lisa",
list1 = {
"X-API-KEY": "XyZzahZaksksXXXYYYOOO000",
"user": {
"email": "Lisa#BLA.com",
"firstName": "Lisa",
"id": "123",
},
"Flat": {
"city": "Munich",
"country": "2",
"countryCode": "DEU",
"currency": "EUR",
"date": "1587671397",
"flatmates": [
{
"email": "Lisa#BLA.com",
"firstName": "Lisa",
"id": "123",
},
{
"email": "Max#BLA.com",
"firstName": "Max",
"id": "124",
},
{
"email": "Hannah#BLA.com",
"firstName": "Hannah",
"id": "125",
},
{
"email": "Kai#BLA.com",
"firstName": "Kai",
"id": "126",
}
],
"founderId": "123",
"id": "99999",
"image": "",
"name": "ABC",
"postCode": "000000",
}
}
list2 = [
{
"creationDate": 1587671663,
"currentUser": 123,
"id": 1717134,
"title": "Do this",
"users": [
124,
126
]
},
{
"creationDate": 1587671663,
"currentUser": 126,
"id": 1717134,
"title": "Do that",
"users": [
123,
125
]
},
{
"creationDate": 1587671821,
"currentUser": 124,
"id": 1717134,
"title": "Clean this",
"users": [
125,
122
]
},
{
"creationDate": 1587671801,
"currentUser": 123,
"id": 1717134,
"title": "Clean that",
"users": [
124,
126
]
}
]
I am pretty new to python.
There are several mind-issues for me since there is a mix between lists and dictionaries in it and how to match/search for values for 2 separate lists/dicts
What I got so far: Iterate over the "CurrentUser"
for user in liste2:
print(user["currentUser"])
Has anyone some approaches?
In pure python with no other modules.
for user in list2:
for mate in list1['Flat']['flatmates']:
if user['currentUser'] == int(mate['id']):
# You found the person now execute this code...
One thing to note that in your list1 you flatmates id is not a integer but a string. So you have to convert that to an int in order to compare the two.

Python & JSON Phrasing issues

I am having issues phrasing the TwitchAPI JSON. I am trying to read the name which is under multiple layers (not Sure of the correct term for this).
Here is part of the API JSON:
{
"_links": {
"next": "https://api.twitch.tv/kraken/channels/test_user/follows?direction=DESC&limit=25&offset=25",
"self": "https://api.twitch.tv/kraken/channels/test_user/follows?direction=DESC&limit=25&offset=0"
},
"_total": 336,
"follows": [
{
"_links": {
"self": "https://api.twitch.tv/kraken/users/test_follower/follows/channels/test_user"
},
"created_at": "2014-07-24T20:21:10Z",
"user": {
"_id": 00000001,
"_links": {
"self": "https://api.twitch.tv/kraken/users/test_follower"
},
"bio": null,
"created_at": "2014-07-05T17:27:45Z",
"display_name": "test_follower",
"logo": null,
"name": "test_follower",
"type": "user",
"updated_at": "2014-07-24T20:20:29Z"
}
},
Etc, it continues with multiple name values I wish to collect.
How do I get the name item? This is my current attempt:
print [data['name'] for data in data['follows']['user']]
But this just gives the error:
TypeError: list indices must be integers, not str
data['follows'] is a list, you can't use ['user'] to get the element in this list.
You need a loop or using data['follows'][0] to get
{
"_links": {
"self": "https://api.twitch.tv/kraken/users/test_follower/follows/channels/test_user"
},
"created_at": "2014-07-24T20:21:10Z",
"user": {
"_id": 00000001,
"_links": {
"self": "https://api.twitch.tv/kraken/users/test_follower"
},
"bio": null,
"created_at": "2014-07-05T17:27:45Z",
"display_name": "test_follower",
"logo": null,
"name": "test_follower",
"type": "user",
"updated_at": "2014-07-24T20:20:29Z"
}
}
So, data['follows'][0]['user'] will get you
"user": {
"_id": 00000001,
"_links": {
"self": "https://api.twitch.tv/kraken/users/test_follower"
},
"bio": null,
"created_at": "2014-07-05T17:27:45Z",
"display_name": "test_follower",
"logo": null,
"name": "test_follower",
"type": "user",
"updated_at": "2014-07-24T20:20:29Z"
}
then you append [name] after it to get the name of the user.
So the answer is: print data['follows'][0]['user']['name']
or
print [data['user']['name'] for data in data['follows']]
The for loop is not correct even if you change data['follows']['user'] to data['follows'][0]['user'], since data['name'] is not valid.
====I CANNOT COMMENT ON ANSWERS=======
The other answer is not correct because there's no 'name' in data['follows']
I think that is something like:
print [data['name'] for data in data['follows']]
I hope this helps

How to get the required content from a JSON string

I have a variable in Robot Frame Work having Json response body in the following format
{
"jsonrpc": "2.0",
"id": "787878",
"result":
{
"content":
[
{
"id": 30,
"userID": "user",
"eventType":
{
"name": "test"
},
"timestamp": "2013-03-13T11:00:28.537Z",
"source": "Service",
"reason": null,
"comment": null,
"dataCache":
{
"lastLogin":
{
"id": 103,
"fieldName": "value1",
"newValue": "Wed Mar 13 07:00:28 EDT 2013",
"oldValue": null,
"type": "java.util.Date",
"auditEvent": null
}
},
"authority": "authenticate",
"auditedObject": null
}
],
"pageNumber": 0,
"pageSize": 99,
"numberOfElements": 1,
"totalElements": 1,
"lastPage": true,
"totalPages": 1
}
}
SO from this How can I get the content of only datacache as shown in the below
{
"lastLogin":
{
"id": 103,
"fieldName": "value1",
"newValue": "Wed Mar 13 07:00:28 EDT 2013",
"oldValue": null,
"type": "java.util.Date",
"auditEvent": null
}
},
If I use a variable like ${variable['result']['content']} , I will get entire body in the content But I just want a body in "DataCache":
Please help me to solve this issue..
${variable['result']['content'][0]['dataCache']}
Is this what you're looking for? Maybe you need some more practice with JSON then...
${variable['result']['content'][0]['dataCache']}
worked in my case.

Categories

Resources