Create a JSON object for a member

Looking to transform the provided page into a JSON object:

var mybody = document.getElementsByTagName('body')[0];
var table = mybody.getElementsByTagName('table')[0];

var jsonObj = [];

for (var i = 0, row; row = table.rows[i]; i++) 
{
    var cell2 = row.cells.length == '1' ? '' : row.cells[1].textContent.trim();
    jsonObj.push( { what: row.cells[0].textContent.trim(), value:cell2 });
}
console.log(jsonObj);

This code generates the following JSON object

[
    Object { what= "Beograd" , value= "" }, 
    Object { what= "Broj leta" , value= "JU 109, JA 1376" }, 
    Object { what= "Avio-kompanija" , value= "JAT AIRWAYS" }, 
    Object { what= "Tip aviona" , value= "AT72" }, 
    Object { what= "Planirano vrijeme" , value= "06:20" }, 
    Object { what= "Status leta" , value= "Odletio" }, 
    Object { what= "" , value= "" }, 
    Object { what= "Beograd" , value= "" }, 
    Object { what= "Broj leta" , value= "SOP 4121" }, 
    Object { what= "Avio-kompanija" , value= "SOLINAIR LTD" }, 
    Object { what= "Tip aviona" , value= "SF34" }, 
    Object { what= "Planirano vrijeme" , value= "16:35" }, 
    Object { what= "Status leta" , value= "Odletio" }, 
    Object { what= "" , value= "" }
]

As the data is for 2 flights on the page, we need to include two elements in the JSON string describing

  1. Flight1
  2. Flight2

To achieve this structure:

 {  "Flight1": [
    Object { what= "Beograd" , value= "" }, 
    Object { what= "Broj leta" , value= "JU 109, JA 1376" }, 
    Object { what= "Avio-kompanija" , value= "JAT AIRWAYS" }, 
    Object { what= "Tip aviona" , value= "AT72" }, 
    Object { what= "Planirano vrijeme" , value= "06:20" }, 
    Object { what= "Status leta" , value= "Odletio" }, 
    Object { what= "" , value= "" }],

"Flight2": [
    Object { what= "Beograd" , value= "" },     
    Object { what= "Broj leta" , value= "SOP 4121" }, 
    Object { what= "Avio-kompanija" , value= "SOLINAIR LTD" }, 
    Object { what= "Tip aviona" , value= "SF34" }, 
    Object { what= "Planirano vrijeme" , value= "16:35" }, 
    Object { what= "Status leta" , value= "Odletio" }, 
    Object { what= "" , value= "" ]

}

Answer №1

Object is considered invalid in JSON formatting.

To ensure the validity of your JSON data, you can use this validator: http://jsonlint.com/

Answer №2

Creating basic JavaScript objects is what you are currently engaged in. Here's an alternative way to accomplish this:

var myObject = {}; // initialize object
myObject["key"] = ["x", "y"]; // establish key-value pairs
myObject.property = {}
myObject.value = 15;

If you want to convert these objects to JSON format, your top choice would be to use JSON.stringify(), a function that transforms JavaScript objects into JSON strings. Additionally, you can utilize $jQuery.parseJSON(), which allows for the conversion of a JSON string back to a JavaScript object. It's important to note that you will need to have jQuery installed to make use of these functions.

Answer №3

To iterate through your objects, you can utilize the <hr> element as a reference point:

var myBody = document.getElementsByTagName('body')[0];
var table = myBody.getElementsByTagName('table')[0];

var dataObject = [], items = {}, itemCount = 1;

for (var j = 0, itemRow; itemRow = table.rows[j]; j++) 
{
    if (itemRow.cells[0].innerHTML == "<hr>") {
        items["Item"+(itemCount++)] = dataObject;
        dataObject = [];
    }
    else {
       var cellValue = itemRow.cells.length == '1' ? '' : itemRow.cells[1].textContent.trim();
       dataObject.push( { key: itemRow.cells[0].textContent.trim(), val:cellValue });
    }
}
console.log(items);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is the div empty? Maybe jQuery knows the answer

I currently have a <div id="slideshow"> element on my website. This div is fully populated in the index.php file, but empty in all other pages (since it's a Joomla module). When the div is full, everything works fine. However, when it's emp ...

What is the best way to make a recursive function display every return value in Javascript?

I need help with a function I have been working on. function main() { //retrieve the start text var start_text = document.getElementById("start_text").value; //retrieve target text var target_text = document.getElementById("target_text"). ...

Which method of loading website images is quicker: sequential or parallel, utilizing Javascript?

As I work on developing an AJAX image gallery that preloads multiple large images ranging from 120kB to 2MB before the lightbox appears, a question arises: should these images be loaded sequentially (waiting for one to preload at a time) or in parallel? Wh ...

Implementing Ajax Like Button functionality in a Ruby on Rails application

I have a Ruby on Rails project that includes a User model and a Content model, among others. I recently implemented a feature where users can "like" content using the acts_as_votable gem. Currently, the liking functionality works as expected but it requir ...

How to Transfer Data from a Dynamic Drop-down Menu to PHP for Processing and Presentation in a Div Element on the Same Web Page

I've scoured various online resources, including StackOverflow, but haven't been able to find a solution for this issue described in the title. On my base page, I have a dynamically generated dropdown list as shown below: <div class="tipfixtu ...

The ASP.net WebMethod seems to be providing a full page output instead of the expected JSON data

I am implementing an auto complete functionality for a textbox. However, when I send a GET request to a web method, instead of receiving the actual data, I get the entire page content. Here is the C# code snippet that I am using: [WebMethod] [Scr ...

filtering elements with selectable functionality in jQuery UI

I'm trying to exclude the <div> children from being selected within this list item and only select the entire <li>. The structure of the HTML is as follows: <ul id="selectable"> <li> <div id="1"></div> ...

Using both withNextIntl and withPlaiceholder simultaneously in a NextJS project causes compatibility issues

I recently upgraded to NextJS 14 and encountered an issue when deploying my project on Vercel. The next.config.mjs file in which I wrapped my nextConfig in two plugins seemed to prevent the build from completing successfully. As a workaround, I decided t ...

Difficulty transmitting Heroku environment variable to Angular CLI application using Node.js

Currently, I am tackling a project that requires passing a stripe key as JSON within Angular. I've stored the key in Heroku config vars and have been attempting to pass that value through the Node.js backend to Angular using the process.env.STRIPE_KE ...

Utilizing TypeScript interfaces to infer React child props

How can I infer the props of the first child element and enforce them in TypeScript? I've been struggling with generics and haven't been able to get the type inference to work. I want to securely pass component props from a wrapper to the first ...

Tips for successfully passing array index as an image source in Vuejs with v-img?

Hi there! I'm currently attempting to cycle through an array of URLs and insert them into the src attribute. I'm struggling with the correct syntax to accomplish this task. Would you be able to lend a hand? I have an array named DataArray that co ...

Is it possible to parse Json using Gson without the need for square brackets around arrays?

Trying to make sense of this json file from a strange format has me quite puzzled. Since I'm new to dealing with Json and using Gson, I feel a bit lost. "2": {"buy_average": 191, "id": 2, "sell_average": 191, "name": "Cannonball", "overall_average" ...

Babel not compiling code correctly

I'm trying to utilize babel to convert client-side ES6 scripts to ES5 and save it to a file. But my current configuration is simply returning the input code. Here's an example of the code: const babel = require('babel-core'); babel. ...

Is there a way to completely clear a form using jQuery in JavaScript?

I have a functioning script that sends emails via Ajax and PHP. However, I am also looking to reset the form after sending an email. Below is my jQuery code: <script src="http://code.jquery.com/jquery-latest.js"></script> <script> $(doc ...

Utilize the ESLint plugin to manage unresolved import paths in Next.js modules

Utilizing module import from next and attempting to import a component as shown below: import Navbar from '@/components/Navbar/Navbar'; Upon running npm run lint, an error is returned stating: 1:20 Error: Unable to resolve path to module &apo ...

What is the method for including the RegExpression value in the request body of a Postman post?

{ "Regex": "^(Common)[_]\d+$|^(MP)[_][0-9a-f]{24}|.*((google)|(Common)|(gmail))+\.(com)$" } I encountered the issue as shown in the screenshot,https://i.sstatic.net/12L7w.png on postman while trying to post the payload wi ...

Validation of the top-level URL

How can I validate or filter only the top-level URL/domain using JavaScript or PHP? This filter should also accept new domain extensions, for example: Valid URL: and so on... Invalid URL: and so on... Subdomains are also not allowed! I need this val ...

Leveraging jQuery plugin within a React ecosystem

While utilizing semantic react, I found myself in need of a date picker. Fortunately, I stumbled upon this library: https://github.com/mdehoog/Semantic-UI-Calendar However, I am unsure how to incorporate it into my react-based project since it's not ...

How does the StreamingContext parameter benefit Json.NET Serialization Callbacks?

I've been trying to grasp the purpose of the StreamingContext parameter in Json.NET Serialization Callbacks. Initially, I thought it would provide access to the current JSON tree being read, but it doesn't seem to work that way. Despite experimen ...

Executing an Ajax request. Best method for transmitting various data elements:

I am currently attempting to perform an ajax call with multiple data inputs. When I send only one string of data, I use the following method: $.ajax({ url: "php/update_lastordning.php", type: "POST", data: "elId=" + elId }); To retrieve t ...