首页 > 解决方案 > Python 解析 JSON 对象并要求选择值

问题描述

我一般是编程新手。我正在尝试制作一个有助于制作零件编号的 Python 脚本。在这里,例如,计算机内存模块。

我有一个 python 脚本需要bmt从 JSON 文件中读取对象。然后要求用户从中进行选择,然后将值附加到字符串中。

{"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"
    }
}}

示例:有一个名为“code”的字符串已经具有值“MMD”。该脚本询问用户从列出的值中选择什么(例如“DR1”)。如果进行了选择(用户输入“DR1”,它将将该值附加到字符串中,新值将是“MMDDR1”。

此代码用于打印 JSON。这就是我已经走了多远

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

我该怎么做呢?

带有其余代码的仓库在这里:https ://github.com/CrazyblocksTechnologies/PyCIPN

标签: pythonjson

解决方案


尝试:

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]

推荐阅读