[Python] Create associative multidimensional array in a loop Python

Discussão em 'Python' iniciado por Stack, Maio 28, 2025.

  1. Stack

    Stack Membro Participativo

    I just started learning Python. I try to get JSON output from wg.conf I'm stuck on creating an array Peers

    { "srv_addr": "10.10.10.1", "srv_port": 123456, "pub_key": "Asdfghh", "prv_key": "Asdfghh", "peers": [ { "comment": "Some Dev", "addr": "10.10.10.2", "pub_key": "SAssadfafa" } ] }

    My code is

    import json
    wg_conf = "/etc/wireguard/wg0.conf"

    iface = ""
    result = {}
    result["peers"] = {}
    i = 0

    with open(wg_conf) as file:
    while line := file.readline():
    if line.startswith("[Interface]"):
    iface = "srv"
    elif line.startswith("[Peer]"):
    iface = "peer"

    if iface == "srv":
    if line.startswith("Address"):
    result["srv_addr"] = line.split()[2]
    if line.startswith("ListenPort"):
    result["srv_port"] = line.split()[2]
    if line.startswith("PrivateKey"):
    result["srv_priv_key"] = line.split()[2]

    elif iface == "peer":
    if line.startswith('#'):
    result["peers"]["peer_comment"] = (line.replace('#', "").replace
    if line.startswith("PublicKey"):
    result["peers"]["peer_pub_key"] = line.split()[2]
    i+= 1
    if line.startswith("AllowedIPs"):
    result["peers"]["peer_allow_ip"] = line.split()[2]


    print (result)

    Continue reading...

Compartilhe esta Página