webenginious webenginious - 4 months ago 12
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
, 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?


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([

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;