'How to retrieve and change data from json file
I am having difficulties accessing my json file from my javascript file. I would like to change the data in the status section of my json file once a submit button is clicked on the webpage. I am aware that I would use ajax to achieve this goal, but I do not know how to access the json file.
This is the db.json file
{
{
"assets": [
{
"id": "0946",
"manufacturer": "SONY",
},
{
"id": "0949",
"manufacturer": "AUDIOTECNIA"
}
],
"transfers": [
{
"id": 1,
"status": "in-progress"
}
]
}
This is my Javascript file
$('form').on('submit', function(e){
e.preventDefault();
parsedData = JSON.parse(db.json);
console.log(parsedData[0].id)
//Changing Status
$.ajax({
type: "PATCH",
url: `http://localhost:3000/transfers/`
});
I've tried using parseData because I read that is how to retrieve the object, from the json file, but I do not believe I am writing it correctly. What documentation or steps would one recommend for solving this issue?
Solution 1:[1]
You missed assets
console.log(parsedData.assets[0].id)
I am assuming this string AND that the file is on a web server since you cannot ajax a file from harddisk
json: "{\"assets\": [{\"id\": \"0946\",\"manufacturer\": \"SONY\"}, {\"id\": \"0949\", \"manufacturer\": \"AUDIOTECNIA\"}],\"transfers\": [{\"id\": 1,\"status\": \"in-progress\"}]}"}
const db = {
json: "{\"assets\": [{\"id\": \"0946\",\"manufacturer\": \"SONY\"}, {\"id\": \"0949\", \"manufacturer\": \"AUDIOTECNIA\"}],\"transfers\": [{\"id\": 1,\"status\": \"in-progress\"}]}"}
parsedData = JSON.parse(db.json);
console.log(parsedData.assets[0].id)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mplungjan |
