簡體   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