Попытка добавить JSON объектов без дублирования кода - PullRequest
0 голосов
/ 02 апреля 2020

Basi c вопрос, но я python noob. У меня есть код, который отлично работает, но он повторяет код, и я хочу перебрать несколько идентификаторов клиентов, сгенерировать JSON и объединить его в один. См. Код ниже.

Код:

#installing packages
import requests
import json 
import datetime 

#organization id
org_id = 123

#keys
certificate_path = 'C:/Users/johndoe/example.pem'
certificate_key_path = 'C:/Users/johndoe/example.key'

######make your api call######

#customer id
custmomer_id_a = 4
custmomer_id_b = 5  

#header info    
headers = {"Authorization": "orgId=%s" % (org_id)}    

#json file being imported for customer reporting
payload = {
               "startTime": '2020-04-27', 
                "endTime": '2020-04-27',
                "timeZone": "ORTZ",
                "granularity": "DAILY",
                "selector": {
                    "orderBy":[{"field":"purchaseRevenue",
                                "sortOrder":"DESCENDING"}], 
                    "fields": ["purchaseCount", 
                               "purchaseRevenue",], 
                    "pagination": { "offset": 0, 
                                   "limit": 1000 }
                    }, 
                "returnRowTotals": False, 
                "returnRecordsWithNoMetrics": True
            }



#url to api server for data
custmomer_a_url = 'https://api.test/%s' % (custmomer_id_a)
custmomer_b_url = 'https://api.test/%s' % (custmomer_id_b)

#response from api pull
custmomer_a_response = requests.post(custmomer_a_url, cert=(certificate_path, certificate_key_path), json=payload, headers=headers)
custmomer_b_response = requests.post(custmomer_b_url, cert=(certificate_path, certificate_key_path), json=payload, headers=headers)


#data returned by api in string format
customer_a_data = json.loads(custmomer_a_response.text) 
customer_b_data = json.loads(custmomer_b_response.text)

Как видите, у меня есть отдельные переменные для customer_a и customer_b. Нужно объединить это в одно. Вот текущий вывод:

Клиент a json:

{'granularity': [{‘purchaseCount': 1, ‘purchaseRevenue': 100, 'purchaseDate': '2020-03-27'}], 'metadata': {customerId': 123, 'customerName': 'John Doe'}}

Клиент b json:

{'granularity': [{‘purchaseCount': 2, ‘purchaseRevenue': 200, 'purchaseDate': '2020-03-27'}], 'metadata': {customerId': 456, 'customerName': 'Jane Doe'}}

Я бы хотел, чтобы это было объединено в один:

Все клиенты json:

{{'granularity': [{‘purchaseCount': 1, ‘purchaseRevenue': 100, 'purchaseDate': '2020-03-27'}], 'metadata': {customerId': 123, 'customerName': 'John Doe'}}, {'granularity': [{‘purchaseCount': 2, ‘purchaseRevenue': 200, 'purchaseDate': '2020-03-27'}], 'metadata': {customerId': 456, 'customerName': 'Jane Doe'}}}

1 Ответ

0 голосов
/ 02 апреля 2020

Вы не можете объединить эти объекты, как вы описываете, но вы можете создать список с вашими customer_a_data и customer_b_data, например:

[{'granularity': [{‘purchaseCount': 1, ‘purchaseRevenue': 100, 'purchaseDate': '2020-03-27'}], 'metadata': {customerId': 123, 'customerName': 'John Doe'}}, {'granularity': [{‘purchaseCount': 2, ‘purchaseRevenue': 200, 'purchaseDate': '2020-03-27'}], 'metadata': {customerId': 456, 'customerName': 'Jane Doe'}}]

, просто сделайте что-то вроде этого:

customers_data = [customer_a_data, customer_b_data]
...