繁体   English   中英

如何在不使用 json 库或没有任何其他库的情况下读取 json 文件到字典或列表中?

[英]how to read json file without using json libarary or without any other libarary in to dictionary or list?

我有一个 JSON 文件,我需要在不使用和库的情况下将其读入字典或列表中。这是我的文件内容。

{
   "101":"Break and Enter Commercial",
   "102":"Break and Enter Residential/Other",
   "103":"Vehicle Collision or Pedestrian Struck (with Fatality)",
   "104":"Vehicle Collision or Pedestrian Struck (with Injury)"
}

这就是我尝试的

def read_codes(filename):
    jsonData = {}
    # empty list to append to it later
    file = open(filename, "r")
    for key in file:
        print(key)
    return jsonData
print(read_codes('codes.json'))

这样的方式怎么样:

with open(file) as f:
    your_dict = eval(f.read().replace('\n', ''))

您可以将其作为文本文件打开。 它会返回您的列表,然后根据您的需要过滤列表。

with open('file.json', 'r') as jsonFile:
    json_obj = jsonFile.readlines()
json_obj = [(obj.rstrip()).lstrip()[:-1] for obj in json_obj[1:-1]]
print(json_obj)

我有一个JSON文件,我需要在不使用and库的情况下将其读入字典或列表中。这是我的文件内容。

{
   "101":"Break and Enter Commercial",
   "102":"Break and Enter Residential/Other",
   "103":"Vehicle Collision or Pedestrian Struck (with Fatality)",
   "104":"Vehicle Collision or Pedestrian Struck (with Injury)"
}

这就是我尝试的

def read_codes(filename):
    jsonData = {}
    # empty list to append to it later
    file = open(filename, "r")
    for key in file:
        print(key)
    return jsonData
print(read_codes('codes.json'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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