skip to Main Content

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!

2

Answers


  1. 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
    Login or Signup to reply.
  2. in case you use by any chance a node.js environment:
    Than you could just install and use

    npm install json2ini
    

    and in your code you could use something like this:

    const json2ini = require('json2ini');
    
    const jsonData = {
      // YOUR JSON-DATA 
    };
    
    const iniData = json2ini(jsonData);
    console.log(iniData);
    

    If not I guess the approach from Lajos Arpad will do the trick.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search