webenginious webenginious - 3 months ago 11
Javascript Question

How to push my JSON data that are displayed in HTML into a final jsonString

SCREENSHOTIn my index.html I display in 5 divs some JSON data(data in JSON format):

<div id="InformationJson" class="messages-container1">{}</div>
<div id="DataJson" class="messages-container2">{}</div>
<div id="RulesJson" class="messages-container3">{}</div>
<div id="WorkitemsJson" class="messages-container4">{}</div>
<div id="LanguageJson" class="messages-container5">{}</div>


In my separate function of my JavaScript code I want to push all my JSON data from these 5 divs in a var named
jsonString
, which will be a final array.

This will be my jsonString implementation:

var jsonString = [push1,push2, push3, push4, push5];


How will I push them all together?

Answer

The contents of those divs may look like JSON to you but, to the computer, they're just strings and will be treated as such.

The most straightforward way to collect them into a larger JSON formatted string would be to convert the strings into Javascript objects via JSON.parse(), insert those objects into a containing object, then convert the whole thing into a string via JSON.stringify().

Extending your intent, you might have something like:

var jsonString = JSON.stringify([
  JSON.parse(push1),
  JSON.parse(push2),
  JSON.parse(push3),
  JSON.parse(push4),
  JSON.parse(push5)
]);


To answer your add-on question of how to extract the content of the divs, it might go like this:

var push1 = document.getElementById('InformationJson').textContent;