How to generate an insert string from json [closed]

0

I'm new and javascript and I need to generate an insert string for sqlite with this string:

{ "InputFile" : "PER_02.inp", "RunTime" : 1492167103, "Reservoir" : "5", "Elevation" : 400.000000, "UpStreamId" : "172", "UpStreamP" : 95.000000, "PRU_l_ID" : "143", "PRU_setting" : 32.531769, "downstream_n_ID" : "164", "downstream_p" : 32.531769, "downstream_l_ID" : "9", "main_flow" : 0.600256, "local_flow_set" : 0.000000, "BLEED1_n_ID" : "6", "BLEED1_demand" : 0.000000, "BLEED2_n_ID" : "7", "BLEED2_demand" : 0.000000, "BLEED3_n_ID" : "8", "BLEED3_demand" : 0.000000, "CRIT1_n_ID" : "153", "CRIT1_p" : 97.513428, "CRIT1_p_set" : 25.000000, "CRIT2_n_ID" : "141", "CRIT2_p" : 104.513039, "CRIT2_p_set" : 0.000000, "CRIT3_n_ID" : "162", "CRIT3_p" : 81.419167, "CRIT3_p_set" : 0.000000, "control_type" : 0 }" 
The table fields have the same names.     
asked by anonymous 12.09.2017 / 04:56

1 answer

1

Considering that if you want to transform JSON into a valid%% query in SQLite, you have to go through the passed object and save the keys and their values. I'll save these values in two vectors, INSERT and chaves , so that valores , when applied to JSON, would return chaves[i] .

  • iterate over the object
  • save the key being iterated in valores[i] , and the value of that key in chaves
  • join valores by merging with commas
  • join chaves merging with commas

    var chaves = [];
    var valores = [];
    var o = { "InputFile" : "PER_02.inp", "RunTime" : 1492167103, /* ignorando o resto por brevidade de escrita e melhor leitura */ };
    for (var chave in o) {
        chaves.push(chave);
    
        // se valor for string, por apóstrofos antes e depois da string
        if (typeof o[chave] === 'string') {
            valores.push("'" + o[chave] + "'");
        } else {
            valores.push(o[chave]);
        }
    }
    
    var insert = "INSERT INTO tabela (" + chaves.join(',') + ") VALUES (" + valores.join(',') + ")";
    
  • 12.09.2017 / 05:23