Home > OS >  Python parse JSON object and ask for selection of values
Python parse JSON object and ask for selection of values

Time:10-12

I am new to programming in general. I am trying to make a Python script that helps with making part numbers. Here, for an example, computer memory modules.

I have a python script that needs to read the bmt object from a JSON file. Then ask the user to select from it then append the value to a string.

{"common": {
    "bmt": {
        "DR1": "DDR",
        "DR2": "DDR2",
        "DR3": "DDR3",
        "DR4": "DDR4",
        "DR5": "DDR5",
        "DR6": "DDR6",
        "FER": "FeRAM",
        "GD1": "GDDR",
        "GD2": "GDDR2",
        "GD3": "GDDR3",
        "GD4": "GDDR4",
        "GD5": "GDDR5",
        "GX5": "GDDR5X",
        "GD6": "GDDR6",
        "GX6": "GDDR6X",
        "LP1": "LPDDR",
        "LP2": "LPDDR2",
        "LP3": "LPDDR3",
        "LP4": "LPDDR4",
        "LX4": "LPDDR4X",
        "LP5": "LPDDR5",
        "MLP": "mDDR",
        "OPX": "Intel Optane/Micron 3D XPoint",
        "SRM": "SRAM",
        "WRM": "WRAM"
    },
    "modtype": {
        "CM": "Custom Module",
        "DD": "DIMM",
        "MD": "MicroDIMM",
        "SD": "SODIMM",
        "SM": "SIMM",
        "SP": "SIPP",
        "UD": "UniDIMM"
    }
}}

Example: There is a string called "code" that already has the value "MMD". The script asks the user what to select from the listed values, (e.g. "DR1"). If a selection is made (user enters "DR1", it appends that value to the string, the new value would be "MMDDR1".

This code is to print the JSON. This is how far I have gotten

def enc(code): 
    memdjson = json.loads("memd.json")
    print(memdjson)

How do I do this?

CodePudding user response:

Try:

import json

def enc(code):
    memdjson = json.load(open("memd.json"))["common"]["bmt"]
    selected = input("Select a value from the following: \n{}\n\n".format(' '.join(memdjson.keys())))
    return code memdjson[selected]

CodePudding user response:

import json
import inquirer

with open(path_to_json_file) as f:
  file  = json.load(f)

code = "MMD"

questions = [
  inquirer.List('input',
                message="Select one of the following:",
                choices=list(file["common"]["bmt"].keys()),
               ),
]

answer = inquirer.prompt(questions)
code  = answer
  • Related