How to generate an Insert string from json

Asked

Viewed 220 times

0

I am new and javascript and need to generate a string from Insert to 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 }" 
Table fields have the same names.

  • Basically, you want to cross members and values and something like that? INSERT INTO tabela (InputFile, Runtime,...) VALUES ('PER_02.inp', 1492167103, ...)

  • That’s right, thank you..

1 answer

1


Taking into account that you want to turn JSON into a query INSERT valid in Sqlite, we have to cross the object passed and save the keys and their values. I will store these values in two vectors, chaves and valores, so that the chaves[i], when applied to JSON, return valores[i].

  1. iterate over the object
  2. keep the key being iterated in chaves, and the value of that key in valores
  3. join together chaves interspersed with commas
  4. join together valores interspersed 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(',') + ")";
    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.