Converting a JSON Object to Key-Value Pairs with Javascript.

We will see how to convert a JSON Object. Well, more like an array of JSON objects to a Key-Value pair.

First, get a JSON object. I will be using this (read the discussion in this link to better understand this object) . It is a list of countries with their dialling and Country Code. There is nothing special about this object other than the fact that I had to once use this dataset and I bookmarked this URL.

First Step : Read the JSON File

Now, i will be using fs module and readFileSync method inside that module that reads the file synchronously. Now depending on your use case you may not want to do that as it blocks function execution till this block of code finishes reading the file.

So, to install fs execute:

npm i fs
function read(){
    let countryCode= fs.readFileSync('countrycode.json');
    return JSON.parse(countryCode);
}

Now when you execute this code. You will get something like this.

Our End goal is to get a Key Value Pair with Key as country code and value a JSON object with dial code, country name and length of the dial code.

Step 2 : Creating Key Value Pair

function createKeyValue(){
    let obj ={};
    let countryCode = read();
    for (let i = 0; i<countryCode.length;i++){
        obj[countryCode[i].code] = {name:countryCode[i].name, dial_code: countryCode[i].dial_code, codeLength: countryCode[i].dial_code.length}
        if(i == countryCode.length -1){
            return obj;
        }
    }
}

So, Lets quickly review this simple Piece of Code we declare an empty object which will store our country code and their dialing codes Key-Value Pair. We call the previously declared function read. Which reads the JSON file and stores it inside a variable called countryCode. Which we will use to create our key-value pair. The code acts as a key here which will store an object that has the name of the country that refers to the code, the dialing code of the country, and the codeLength the length of the dialing code. It returns the key-value pair object.

Now this function when executed returns us the key-value Pair. At this point, we already have what we set to achieve but in case you wanted to write in the file, we can create another function that does so.

(Optional) Write the Key-Value pair to file.

function write(){
    let keyValuePair = JSON.stringify(createKeyValue())
    fs.writeFileSync('countrycode.json', keyValuePair);
}

We use writeFileSync which will block further execution of code till this completes. So you may want to use writeFile instead. The function is simple and just calls createKeyValue() which is explained above.

And Voila we have our key value Pair file with the name countrycode.json ready. Now you can use Asynchronous read and write file method to better suit your needs.

Leave a Reply