Search code examples
jsonini

How to convert JSON to INI-Format


i would like to know, if there is a way with javascript or typescript to convert JSON to INI-Format. Im New­bie.

from:

{
"peerEndpoint": "blub.bla:49997",
"peerPublicKey": "dfasdfasfsdfasdfa",
"deviceIPs": [
  "10.40.16.1"
],
"peerAllowedIPs": [
  "10.40.16.0/22",
  "10.40.0.0/20"
],
"applications": {}
}

to:

Address = 10.40.16.1/32
[Peer]
PublicKey = dfasdfasfsdfasdfa
Endpoint = blub.bla:49997
AllowedIPs = 10.40.16.0/22, 10.40.0.0/20

thank you so much in advance!


Solution

  • Of course. See below:

    /*
    Address = 10.40.16.1/32
    [Peer]
    PublicKey = dfasdfasfsdfasdfa
    Endpoint = blub.bla:49997
    AllowedIPs = 10.40.16.0/22, 10.40.0.0/20
    */
    let json = {
    "peerEndpoint": "blub.bla:49997",
    "peerPublicKey": "dfasdfasfsdfasdfa",
    "deviceIPs": [
      "10.40.16.1"
    ],
    "peerAllowedIPs": [
      "10.40.16.0/22",
      "10.40.0.0/20"
    ],
    "applications": {}
    }
    
    function displayIPs(arr) {
        return arr.map(item => item + ((item.indexOf("/") === -1) ? "/32" : "")).join(",");
    }
    
    let template = `Address = ${displayIPs(json.deviceIPs)}<br>[Peer]<br>`;
    let jsonKeys = ['peerEndpoint', 'peerPublicKey', 'peerAllowedIPs'];
    for (let key of jsonKeys) {
        if (key.indexOf("peer") === 0) {
            let k = key.substring(4);
            template += `${k} = ${(k === "AllowedIP") ? displayIPs(json[key]) : json[key]}<br>`;
        }
    }
    
    document.write(template);

    Explanation:

    • we create a json
    • we define a function that takes an IP address and defaults its end to /32 if there is no port defined
    • we create a template, using template literals, using this helper function to cope with the address
    • we create a set of peer keys to ensure the order of our items
    • we loop this set
    • and for each item, we handle its values as IP addresses if needed and add them as they are otherwise