簡體   English   中英

配置解析器 Python - 如何從 json 文件中讀取?

[英]Config Parser Python - How to read from json file?

我在與我的script/.py相同的文件夾中創建了一個profile.json文件。 它看起來像:

{
    "name": "",
    "lastname": "",
    "age": "",
    "city": "",
}

我希望將其插入到我的腳本中,該腳本的標題為:

"info": {
    "given_name": "",
    "given_Lastname": "",
    "given_age": "",
    "given_city": ""
}

我想知道如何才能將我的profile.json讀取到我的腳本中? 這是我第一次使用它,我也是 Python 的新手。 我覺得這可能是一種無需每次都更改代碼即可輕松修改信息的方法。

編輯:

試圖這樣做:

使用 open('profile.json', encoding='UTF-8') 作為 json_data: config = json.load(json_data) print(config)

然后:

"info": 
       {
         "given_name": config.given_name
       }

打印出來的信息很好,但是當涉及到“given_name”時:config.given_name然后我收到一個錯誤說

AttributeError: 'dict' object has no attribute 'given_name'

對您的原始問題的評論中有一些很好的建議。 如果您想從另一個文件中提取可配置數據,您可以通過查看原始問題來做兩個選擇。

1.使用json文件

看起來這是第一個建議的答案,您可以從此 JSON 文件配置可以在程序中使用的變量。 假設 config.json 文件位於程序的當前目錄中,您可以執行以下操作:

import json

with open('config.json', 'r') as config_file:
    config_data = json.load(config_file)

2.使用python文件

這是另一個選項,以防萬一您不想在加載配置時反序列化 json。 您可以將所有內容保留為 python 數據類型,因此您只需要導入它。 在此示例中,CONFIG_INFO 只是一個字典,您可以將其導入到需要它的其他腳本中。 我通常將它用於工作中的用戶名/密碼/常規配置內容。

配置文件

CONFIG_INFO: {
    "given_name": "test name",
    "given_lastname": "test lastname",
    "given_age": 12,
    "given_city": "Seattle"
}

my_script.py

from config import CONFIG_INFO

print("Config City: {0}".format(CONFIG_INFO["given_city"]))
print("Config Name: {0}".format(CONFIG_INFO["given_name"]))
print("Config Lastname: {0}".format(CONFIG_INFO["given_lastname"]))
print("Config Age: {0}".format(CONFIG_INFO["given_age"]))

問題是您試圖將字典鍵作為屬性訪問(即: config["given_name"]config.given_name 。您也多次更改了您的問題,但是您正在嘗試做什么(我認為) 很簡單。對於您給出的簡單示例,其中只有一個 json 對象的 json 文件,這可能更接近您要執行的操作:

*注意:你的json語法是錯誤的,應該是{ "info": { ... } }

#!/usr/bin/env python3
'''profile.json:
{
    "name": "steve",
    "lastname": "jobs",
    "age": "70",
    "city": "heaven"
}
'''
import json
import io


# Open the JSON File and create a StringIO buffer to hold data
with open('profile.json', 'r') as datafile, io.StringIO() as data:
    # Load data into json file
    config = json.load(datafile)
    # Build json strong
    data.write(f'''{{
            \r\t"info": {{
            \r\t\t"given_name": "{config['name']}",
            \r\t\t"given_Lastname": "{config['lastname']}",
            \r\t\t"given_age": "{config['age']}",
            \r\t\t"given_city": "{config['city']}"
            \r\t}}\n}}''')
    print(data.getvalue())
    # open a new file to save the data (overwrite if it exists)
    with open('newfile.json', 'w') as outfile:
        # load the json string and dump to outfile
        deserialized = json.loads(data.getvalue())
        json.dump(deserialized, outfile)
        # newfile.json:
        #{
        #        "info": {
        #                "given_name": "steve",
        #                "given_Lastname": "jobs",
        #                "given_age": "70",
        #                "given_city": "heaven"
        #        }
        #}

這只是您提供給我的數據的一個簡單示例,因此我制作了另一個使用 json 列表而不是 json dict 的示例:

[{
    "name": "steve",
    "lastname": "jobs",
    "age": "70",
    "city": "heaven"
},
{
    "name": "steve1",
    "lastname": "jobs1",
    "age": "71",
    "city": "heaven1"
},
{
    "name": "steve2",
    "lastname": "jobs2",
    "age": "72",
    "city": "heaven2"
},
{
    "name": "steve3",
    "lastname": "jobs3",
    "age": "73",
    "city": "heaven3"
},
{
    "name": "steve4",
    "lastname": "jobs4",
    "age": "74",
    "city": "heaven4"
}]

還有一個類似的腳本:

#!/usr/bin/env python3
'''profile.json:
'''
import json
import io


# Open the JSON File and create a StringIO buffer to hold data
# Note: StringIO provides a file-like interface over a string
with open('profile.json', 'r') as datafile, io.StringIO() as data:
    # Load data into json file
    config = json.load(datafile)
    # Build json strong
    data.write('{\n\t"info": [\n')
    #data.write('\t{')
    for jsonobj in config:
        data.write(f'''\t    {{
                \r\t\t"given_name": "{jsonobj['name']}",
                \r\t\t"given_Lastname": "{jsonobj['lastname']}",
                \r\t\t"given_age": "{jsonobj['age']}",
                \r\t\t"given_city": "{jsonobj['city']}"
                \r\t    }}''')

        # Note: There is a bug here.
        # This will not be able to handle duplicate objects in
        # the json list. For a trivial example like this, it works.
        if jsonobj == config[-1]:
            data.write('\n\t]\n}')
        else:
            data.write(',\n')
    # open a new file to save the data (overwrite if it exists)
    with open('newfile.json', 'w') as outfile:
        # We need to serialize the json data if we want to write to file
        deserialized = json.loads(data.getvalue())
        outfile.write(json.dumps(serialized))
        # or we can just print it
        print(serialized)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM