首页 > 解决方案 > 如何使用python读取json文件并根据ID打印json正文

问题描述

我有一个 json 文件,其数据如下:

 {
   "A": "ID",
   "B": "Priority",
   "C": "Match URL",
   "D": "Match Query",
   "E": "Redirect URL",
   "F": "Status Code",
   "G": "Descr.",
   "H": "Type",
   "I": "Mode",
   "J": "Preserve Query",
   "K": "Start Date",
   "L": "End Date",
   "M": "Actions"
 },
 {
   "A": "24141",
   "B": "",
   "C": "/s/l",
   "D": "",
   "E": "http://local.tb.hello.com/markets/abc.hello.com/mobile/smsLanding.html",
   "F": "0",
   "G": "",
   "H": "String",
   "I": "Internal",
   "J": "",
   "K": "",
   "L": "",
   "M": "Toggle Dropdown"
 },
 {
   "A": "26875",
   "B": "",
   "C": "/l",
   "D": "",
   "E": "http://local.tb.hello.com/markets/abc.hello.com/mobile/smsLanding.html",
   "F": "0",
   "G": "",
   "H": "String",
   "I": "Internal",
   "J": "",
   "K": "",
   "L": "",
   "M": "Toggle Dropdown"
 },

我正在尝试读取上述 json 文件的文件并根据 ID 打印整个正文。例如:如果我输入的 ID 为 24141,我应该得到下面的 json 格式:

{
   "A": "24141",
   "B": "",
   "C": "/s/l",
   "D": "",
   "E": "http://local.tb.hello.com/markets/abc.hello.com/mobile/smsLanding.html",
   "F": "0",
   "G": "",
   "H": "String",
   "I": "Internal",
   "J": "",
   "K": "",
   "L": "",
   "M": "Toggle Dropdown"
 }

请帮助如何实现这一目标。我是 python 新手,所以尝试读取文件,它可以保存在字符串变量中,但无法将其转换回 json 并基于 id。

标签: pythonjson

解决方案


一个简单的方法。可能有更高性能的路线。

dd = {Define your json file.}
result = None
find_item = '26875'
for d in dd:
    item = d.get('A', None)
    if find_item == item:
        result = d
        break
print(result)

推荐阅读