Skip to content

Instantly share code, notes, and snippets.

@farhad-taran
Last active March 30, 2023 19:56
Show Gist options
  • Save farhad-taran/19e49877a90ba0fd2f95a34671e291f4 to your computer and use it in GitHub Desktop.
Save farhad-taran/19e49877a90ba0fd2f95a34671e291f4 to your computer and use it in GitHub Desktop.
Converting JSON to a text based flat file of key value pairs

Editing json files inline for non technical people could be challening and error prone, therefor we have opted to convert json files to flat file formats comprising of key value, the following script can convert a javascript object to such format:

var o = { 
    foo:"bar",
    arr:[1,2,3],
    subo: {
        foo2:"bar2"
    }
};

function traverse(o,keyPath,lines) {
    for (var key in o) {
        keyPath = `${keyPath}_${key}`;
        if (o[key] !== null && typeof(o[key])=="object") {

            //going one step down in the object tree!!
            traverse(o[key],keyPath,lines);
        }
        else
        {
            lines.push(`${keyPath.replace(/(^\_+|\_+$)/mg, '')}=${o[key]}`);
        }
    }
}

let lines = [];

traverse(o,'',lines);
console.log(lines);

and the output:

'foo=bar',
'foo_arr_0=1',
'foo_arr_0_1=2',
'foo_arr_0_1_2=3',
'foo_arr_subo_foo2=bar2'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment