Let's say I have this JSON
{
"pelicula":[
{
"Titulo":"La vida es bella",
"Director":"Roberto Benigni"
}
{
"Titulo":"Jurassic park",
"Director":"Steven Spielberg"
}
]
}
And I want to add more movies to this JSON, through a form, and that information is saved in the JSON file. Is it possible to do that?
Yes, it is possible, and we are going to take the JSON as an example, for this we need to create an html form where we pass the data.
for this we will create our index
index.html
Where we will have 3 fields (Title, Director and Release Date), if we want to add more, we can do it later. Once your form is created with your ids, we create 2 js files (at least that's how I handle it).
In the first we will have the JSON data and in the other, all the js logic.
interfaz.js
Here we declare an array where we will be storing the data that will be added to your form, using the
agregarDatosPelicula()
. In this function, what you tell it is to create an objectNuevaPelicula
where you will store your data in json format. Then all this, you add it to your data movies array with the methodpeliculasDatos.push(NuevaPelicua);
Once this is understood, let's go to the logic of all this
logica.js
Here we are interested in obtaining the data that the inputs have when giving it submit, that is why we obtain the id of the button and all that will be stored in a function called
guardarDatosPeliculas()
Which is nothing more than a call to all the inputs (with their respective id), these will be saved in the functionagregarDatosPeliculas()
(since we have access to the newMovie object and its data).Finally we have to print all this in a table (for this example take it into account). and with it, display the data you get from the inputs.
Creating a list variable which gets the list of movies and returns them. We also declare where they will be displayed, in this case tbody and its respective id. It cleans up any data in it
<body></body>
with innerHTML.We will create a for loop that as long as the size of the list is less than i, our row variable will be inserting data that you have in your json file into tbody.
in this case, we have 3:
titulo, director y Lanzamiento
which with the methodinsertCell()
we will tell you in which positions they should be added. Finally, with innerHTML we clean and insert withlista[i].propiedad...
remember that in var
NuevaPelicula
we put the property, and this particular example has 3.title, director y date
I hope I have explained myself well, if you have any questions, I will gladly answer you.
EDIT1:
If you want to add more data, you must modify your form by adding the field you want, in interface.js add another data in
agregarDatosPelicula(... varN)
and also inNuevaPelicula
finally, add them
guardarDatosPelicula()
with their respective id and print it so that it can be displayed in your htmlBut how do you save movies to a JSON file to retrieve it on opening?