简体   繁体   中英

Is there an efficient way to write data to a JSON file using a dictionary in Python?

I'm writing a program in Python to use an API that needs to get input from a JSON payload in a really specific way which is shown below. The poid element will contain a different number with each run of the program, the inventories element contains a list of dictionaries that I am trying to send to the API.

[
    {   
        "poid":"22130",
        "inventories": 
        [        
            {       
                "item": "SAMPLE-ITEM-1",
                "mfgr": "SAMPLE-MANUFACTURER-1",
                "quantity": "1",
                "condition": "REF"
            },
            {       
                "item": "SAMPLE-ITEM-2",
                "mfgr": "SAMPLE-MANUFACTURER-2",
                "quantity": "3",
                "condition": "REF"
            }
        ]   
    }
]

The data I need to put into the file is stored in a dictionary and a list as shown below. For simplicity of this post, I'm showing what the dictionary and list would look like after another method creates them. I'm not sure if this is the most efficient way of storing this data when I'm having to write it to JSON.

pn_and_mfgr_dict = {'SAMPLE-ITEM-1': 'SAMPLE-MANUFACTURER-1', 'SAMPLE-ITEM-2': 'SAMPLE-MANUFACTURER-2'}
quantities = ["1","3"] 
poid = 22130 #this will be different each run

If it makes sense from what I've written above, I need to generate a JSON file that looks like the first codeblock given the information from the second codeblock. The item at index 0 in the quantities list corresponds to the first key/value pair in the dictionary and so on. The "condition" value in the first codeblock will always have "REF" as its value for my use, but I need to also include that in the final payload that gets sent to the API. Since the part number and manufacturer dictionary will be a different length with each run, I also need this method to work regardless of how many values are in the dictionary. This dictionary and the quantities list will always be the same length though. I think the best way I can solve this is making a for loop that iterates through the dictionary and puts respective data where it needs to be, then reading the file when the for loop is done and sending it as the payload but please correct me if there's a better way to do this like storing everything in variables. I also have no experience with JSON so I have attempted to use JSON libraries to accomplish this with no idea what I'm doing wrong. I can edit this with my attempts tonight but I wanted to post this as soon as possible.

Here is one possible solution:

import json

pn_and_mfgr_dict = {
    'SAMPLE-ITEM-1': 'SAMPLE-MANUFACTURER-1',
    'SAMPLE-ITEM-2': 'SAMPLE-MANUFACTURER-2'
}

quantities = ['1', '3'] 

poid = 22130

payload = {
    'poid': poid, 
    'inventories': [{
        'item': item,
        'mfgr': mfgr,
        'quantity': quantity,
        'condition': 'REF'
      } for (item, mfgr), quantity in zip(pn_and_mfgr_dict.items(), quantities)]
}

print(json.dumps(payload, indent=2))

The code above will result in:

{
  "poid": 22130,
  "inventories": [
    {
      "item": "SAMPLE-ITEM-1",
      "mfgr": "SAMPLE-MANUFACTURER-1",
      "quantity": "1",
      "condition": "REF"
    },
    {
      "item": "SAMPLE-ITEM-2",
      "mfgr": "SAMPLE-MANUFACTURER-2",
      "quantity": "3",
      "condition": "REF"
    }
  ]
}

Naturally, you can adjust that for multiple poids with something like this:

poids = [22130, 22131, 22132]

for poid in poids:
    # implement here the logic to get items and quantities for
    # each poid

    payload = {
        'poid': poid,
        'inventories': [{
            'item': item,
            'mfgr': mfgr,
            'quantity': quantity,
            'condition': 'REF'
          } for (item, mfgr), quantity in zip(pn_and_mfgr_dict.items(), quantities)]
    }

    print(json.dumps(payload, indent=2))

You will need to change it to have the correspondents items and quantities for each poid , and I leave that as starting point for you to implement.

Your second block is your input, so you could immediately start by write down a function taking those input and returning a JSON string.

import json
from typing import Dict, List


def jsonify_data(pn_and_mfgr_dict: Dict, quantities: List, poid: int):
    constructed_data = []  # TODO
    return json.dumps(constructed_data)

Then you could start working on using the inputs to construct the output data you desired. And you already know how to do it.

I think the best way I can solve this is making a for loop that iterates through the dictionary and puts respective data where it needs to be

Yes, that's the way to do it.

Here's my version of solution:

import json
from typing import Dict, List


def jsonify_data(pn_and_mfgr_dict: Dict, quantities: List, poid: int):
    inventories = [
        {
            'item': item,
            'mfgr': mfgr,
            'quantity': quantity,
            'condition': 'REF',
        } for (item, mfgr), quantity in zip(pn_and_mfgr_dict.items(), quantities)
    ]
    constructed_data = [
        {
            'poid': f'{poid}',
            'inventories': inventories,
        }
    ]
    return json.dumps(constructed_data)
import json

data = {'inventories': [{'SAMPLE-ITEM-1': 'SAMPLE-MANUFACTURER-1'}, {'SAMPLE-ITEM-2': 'SAMPLE-MANUFACTURER-2'}]}
quantities = ["1", "3"]
poid = 22130

# Add poid to data
data['poid'] = poid

# Add quantities to data
for item in data['inventories']:
    item['quantity'] = quantities.pop(0)

# Serializing json
json_object = json.dumps(data, indent=4)
print(json_object)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM