Read and Edit JSON File via JS!

Asked

Viewed 595 times

1

So guys, I want to understand how JSON file reading and editing works. I’ve tried so many ways, but without any results. I will leave the base structure I already have here to understand my goal.

HTML:

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Teste de DB</title>

    <link rel="stylesheet" href="Semantic/semantic.min.css">
</head>
<body onload="tablelist()">
    <br>
    <h1 align="center">Resultado de banco de dados</h1>
    <div class="ui container">
        <div class="ui raised segment">
            <br>
            <!-- Texts -->
            <div class="ui fluid input">
                <input required id="ID" type="number" placeholder="ID">
            </div>
            <br>
            <div class="ui fluid input">
                <input required id="Money" type="number" placeholder="Money">
            </div>
            <br>
            <div class="ui fluid input">
                <input required id="Bank" type="number" placeholder="Bank">
            </div>

            <!-- Buttons -->
            <div class="ui basic center aligned segment">
                <div id="useradd" onclick="add_db()" class="ui green button"><i class="icon plus"></i> Adicionar ID</div>
                <div id="userdel" onclick="del_db()" class="ui red button"><i class="icon delete"></i> Remover ID</div>
            </div>

            <!-- Table -->
            <table class="ui inverted blue table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Money</th>
                        <th>Bank</th>
                    </tr>
                </thead>
                <tbody id="db_data">
                        
                </tbody>
            </table>
        </div>
    </div>

    <!-- Script -->
    <script src="js/index.js"></script>
    <script src="js/jQuery.js"></script>
    <script src="Semantic/semantic.min.js"></script>
</body>
</html>

My JS code I left only the import of the html data, the JSON file I don’t know how to do, however it is located in "db/database.json"

JS:

//Buttons
let useradd = document.getElementById('useradd')
let userdel = document.getElementById('userdel')

//Texts
let userid = document.getElementById('ID')
let usermoney = document.getElementById('Money')
let userbank = document.getElementById('Bank')

//Table
let tablebody = document.getElementById('db_data')

//Functions
function tablelist(){
    tablebody.innerHTML +=  '<tr><td>0001</td><td>500</td><td>2000</td></tr>'
    tablebody.innerHTML +=  '<tr><td>0002</td><td>200</td><td>1300</td></tr>'
}
function add_db(){}
function del_db(){}

JSON:

{
    "users":[
        {"0001":[
            {"Money":"500"},
            {"Bank":"2000"}
        ]},
        {"0002":[
            {"Money":"200"},
            {"Bank":"1300"}
        ]}
    ]
}

Visually it’s like this:

inserir a descrição da imagem aqui

My goal is to insert the 3 values to add a new "user" to the JSON file and insert only the ID to remove the "user". The table will be updated when loading the page, I left as an example in the function code tablelist().

1 answer

0

In this case it would be necessary to write the amendments in back-end

If it’s something totally temporary, no Client-Side just use the

var jsonObj = {"users":[{"0001":[{"Money":"500"},{"Bank":"2000"}]},{"0002":[{"Money":"200"},{"Bank":"1300"}]}]}; // obtem esses dados do db/banco.json e realiza a alteração..
localStorage.setItem('jsonObj', JSON.stringify(jsonObj)); // salva no localStorage

// para obter o jsonObj do localStorage
var jsonObj = JSON.parse(localStorage.getItem('jsonObj'));

But if it is something you really want to change in the file json bank. overall. What if the Engines you are using are only JavaScript send a POST with the obj modified for the back-end (Node.js, Php, ...) and every time you make a call, the data from jsonObj = {}; will be updated.

fetch('url', {method: 'post', mode: 'cors', body: JSON.stringify(jsonObj)})
.then((response) => {
    return response.json();
}).then((resJsonObj) => {
    //retorno do json modificado..
    //dai aqui você renderiza os dados da forma que quiser, nos respectivos campos (Id, Money e Bank)
});

I believe this is not exactly the way you want it, but I hope I may have helped you in some way. Good luck!

Browser other questions tagged

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