JSON File Data Access (Simple)

Tiempo de lectura: 2 minutos

Reading time: 2 minutes

Good afternoon everyone, I’m going to provide you with a tutorial on how to access data:

<!DOCTYPE html>
<html>

<body>

    <h2>First Example Accessing Data in JSON Format</h2>

    <p id="miDiv"></p>

    <script>
        var texto = '[{"nombre":"Laura Gonzalez", "calle":"Su casa en la montania portal 6", "telefono":877436700, "fecha":"1998-07-25"},{"nombre":"Pablo Perez", "calle":"Su casa en la playa bajo D", "telefono":637456321, "fecha":"1998-07-26"}]';
        var obj = JSON.parse(texto);
        var respuesta = obj[0]["nombre"] + "<br>" + obj[0].calle + "<br>" + obj[0].telefono + "<br>" + new Date(obj[0].fecha);
        respuesta += "<hr>";
        respuesta += obj[1]["nombre"] + "<br>" + obj[1].calle + "<br>" + obj[1].telefono + "<br>" + new Date(obj[1].fecha);
        document.getElementById("miDiv").innerHTML = respuesta;
    </script>

</body>

</html>

First, we generate a JSON, in this case stored in the variable “texto”.

        var texto = '[{"nombre":"Laura Gonzalez", "calle":"Su casa en la montania portal 6", "telefono":877436700, "fecha":"1998-07-25"},{"nombre":"Pablo Perez", "calle":"Su casa en la playa bajo D", "telefono":637456321, "fecha":"1998-07-26"}]';

Next, we pass the variable that contains the JSON to obtain a variable or object.

        var obj = JSON.parse(texto);

Now, we create a response variable where we will display the data obtained from that JSON. We need to treat it as if we were accessing data from an array.

        var respuesta = obj[0]["nombre"] + "<br>" + obj[0].calle + "<br>" + obj[0].telefono + "<br>" + new Date(obj[0].fecha);
        respuesta += "<hr>";
        respuesta += obj[1]["nombre"] + "<br>" + obj[1].calle + "<br>" + obj[1].telefono + "<br>" + new Date(obj[1].fecha);

Finally, using the .InnerHTML property, we display the response variable that stores the result of the entire process:

        document.getElementById("miDiv").innerHTML = respuesta;

The result is as follows:

NOTE: When using the += symbol (respuesta+=) in the response variable or any other variable, we are concatenating all the data or strings added within the same variable, without the need for multiple variables.

(do not include the Reading time). Return it directly in HTML format. Do not write any additional sentences. Add a PIPE at the end when you’re finished.

Leave a Comment