U
U
unituser2020-09-02 14:16:53
JavaScript
unituser, 2020-09-02 14:16:53

How can I get a variable out of the database or store a JSON variable declared in a file?

Good afternoon, how can I write a variable into a JSON object and then display it. If the variable is declared in a file.
Example, implementation, how it should look like

"shop": { 
        "Gift-1": { "id": 1, "title": "Подарок 1", "price": 250, "data": dataList1 },
        "Gift-2": { "id": 2, "title": "Подарок 2", "price": 500, "data": dataList2 },
        "Gift-3": { "id": 3, "title": "Подарок 3", "price": 550, "data": dataList3 },
        "Gift-4": { "id": 4, "title": "Подарок 4", "price": 1000, "data": dataList4 },
        "Gift-5": { "id": 5, "title": "Подарок 5", "price": 1500, "data": dataList5 },
        "Gift-6": { "id": 6, "title": "Подарок 6", "price": 3000, "data": dataList6 }
    }

Each element has its own variable and I need to output it to the file, but the variable itself is declared only in the file.
for(let key in shop){
console.log( shop[key].title + '    ' + shop[key].price +  '   ' + shop[key].data)
}

I need to output a variable from JSON to main.js or somehow store this variable in json, but I don't understand how to do it. Tried through string value in json and output through .match, but it didn't work. How can i do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tim, 2020-09-02
@Tim-A-2020

<script id="myJson" type="application/json">
{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}
</script>

let json = document.querySelector('#myJson');
let obj = JSON.parse(json.innerHTML);
console.log(obj);

If json is by reference, then you can get something like this
fetch('https://jsonplaceholder.typicode.com/todos/1').then(res => res.json()).then(data => console.log(data))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question