Creating the correct JSON structureHere is how you can format JSON

I have a snippet of javascript code that I'm utilizing with casperjs to iterate through links and retrieve data in json format.

Below is the code snippet:


casper.each(links, function (self, link) {

this.thenOpen(link, function () {
    // obtain work order information
    var town_selector = 'div tr';
    var town_names_info = this.getElementsInfo(town_selector);
    var town_names = [];
    for (var i = 0; i < town_names_info.length; i++) {
        town_names.push(town_names_info[i].text.trim().replace(/\n\s+\n/, ''));
    }
    var jsonTest = arrayToObject(town_names);
    json.push(JSON.stringify(jsonTest));
    casper.capture('./images/workOrder' + workOrder + '.png');
    workOrder++
    utils.dump(jsonTest);
    array.push(jsonTest);
    casper.thenClick(x('/html/body/table[2]/tbody/tr/td[2]/a[2]'), function () {
        // carry out some additional tasks here 
        someLinks = this.evaluate(getLinks);

        for (var i = 0; i < someLinks.length; i++) {
            someLinks[i] = "https://somelink" + someLinks[i];
        }
        casper.each(someLinks, function (self, link) {
            self.thenOpen(link, function () {
                var selector = 'div tr';
                var names_info = this.getElementsInfo(town_selector);
                var names = [];
                for (var i = 0; i < names_info.length; i++) {
                    names.push(names_info[i].text.trim().replace(/\n\s+\n/, ''));
                }
                var jsonTest = arrayToObject(names);
                json.push(JSON.stringify(jsonTest));
                utils.dump(jsonTest);
                array.push(jsonTest);
                fs.write('results.json', JSON.stringify(array), 'w');
                casper.capture('./images/lineItem' + lineItem + '.png');
                lineItem++
            });
         });
      });
   });
});

The following shows the output for two activities each with two line items:


     [{"Activity #":"some activity",
       "Customer":"some customer",
       "Account #":"some account"},
      {
       "Line #":"1",
       "Action Required":"",
       "Status":"some status",
       "Product Line":"some product line",
       "Product":"some product"},
      {
       "Line #":"2",
       "Action Required":"",
       "Status":"some status",
       "Product Line":"some product line",
       "Product":"some product"},
      {
       "Activity #":"some other activity",
       "Customer":"some other customer",
       "Account #":"some other account"},
      {
       "Line #":"1",
       "Action Required":"",
       "Status":"some status",
       "Product Line":"some product line",
       "Product":"some product"},
      {
       "Line #":"2",
       "Action Required":"",
       "Status":"some status",
       "Product Line":"some product line",
       "Product":"some product"}]

Please assist me in transforming my output to resemble the following structure:


     [{
         "Activity #": "some activity",
         "Customer": "some customer",
         "Account #": "some account",
         "lineItems": [
             {
                 "Line #": "1",
                 "Action Required": "",
                 "Status": "some status",
                 "Product Line": "some product line",
                 "Product": "some product"
             },
             {
                 "Line #": "2",
                 "Action Required": "",
                 "Status": "some status",
                 "Product Line": "some product line",
                 "Product": "some product"
             }
         ]
     },
     {
         "Activity #": "some activity",
         "Customer": "some customer",
         "Account #": "some account",
         "lineItems": [
             {
                 "Line #": "1",
                 "Action Required": "",
                 "Status": "some status",
                 "Product Line": "some product line",
                 "Product": "some product"
             },
             {
                 "Line #": "2",
                 "Action Required": "",
                 "Status": "some status",
                 "Product Line": "some product line",
                 "Product": "some product"
             }
         ]
     }]

Thank you for your assistance.

Answer №1

If you utilize the correct parameters with JSON.stringify, you can achieve this task:

fs.write('results.json', JSON.stringify(dataArray, null, 4), 'w');

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

Guide on creating 2 select inputs with distinct elements?

Imagine you have two select inputs called 'Favorite Fruits' and 'Least Favorite Fruits'. Both of them contain a list of 5 fruits. // The following code is an example to demonstrate the issue <select name='favoriteFruits'& ...

What causes the mismatch between JSONschema and JSON data?

After analyzing the json provided: { "msg":"aaaa", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4120202001262c20282d6f222e2c">[email protected]</a>" } I proceede ...

Pair of dimensions painting with d3 version 4

I am having trouble converting my code from d3 v3 to d3 v4 Below is the original code snippet: var brush = d3.svg.brush() .x(x) .y(y) .on("brushstart", brushstart) .on("brush", brushmove) .on("brushend", brushend); However ...

Getting the WebElement object by manually clicking an element while in an active WebDriver Session

I am currently developing a Java Swing application for managing object repositories in Selenium scripts. This application will launch a WebDriver instance and allow users to manually navigate to the desired element for inspection. My goal is to capture th ...

Receiving a null value when attempting to access the ids of dynamically created HTML elements using JavaScript

Encountering issue with accessing ids of dynamically generated HTML elements using javascript In my current project, I am attempting to dynamically alter the ids of div elements and remove buttons that are appended to the parent div. The desired functiona ...

Revamp the HTML table with JavaScript headers

I imported data from a CSV file into an HTML table and here is how it appears: <div id="myTable" style="-ms-overflow-x: auto;"> <table> <tbody> <tr class="rownum-0"> <td>Make</td> ...

SQL Server integration with JSON formatting

I need assistance in formatting the JSON file provided below into a table. The JSON file is fetched from a REST API. I have attempted to use OPENJSON and CROSS APPLYS to achieve this, but so far, I have only received zero values in return. Is there a ...

Using Json.Net: Learning to Exclude Null Elements When Deserializing Array JSON Data

My JSON data looks like this: { "Variable1": "1", "Variable2": "50000", "ArrayObject": [null] } In my code, I have the following stubs: public class Class1 { public string Variable1 { get; se ...

Navigating through nested JSON Objects for dropdown functionality in Angular 6 - a step-by-step guide

Currently, I am facing a challenge in Angular 6.0 where I am trying to use HttpClient to iterate through JSON data retrieved from a local file within my assets folder. Below is the sample JSON Data: [{ "configKey": [{ "user1": [{ ...

Deciphering the creation process behind the "WhatsApp Web" front-end page

I'm currently exploring the creation process of the front-end page for WhatsApp Web, specifically focusing on the list of contacts located on the left side (<div id="pane-side">). The contact names within this list are identified by the class "e ...

What could be the reason for the unexpected outcome when checking if display is equal to "none"?

I have a JavaScript function called "display()". I want to hide my navigation menu on click, but it is not working properly - it just blinks. I am looking for a solution that uses only JavaScript and does not involve querySelector. function display() { ...

When debugging in ASP MVC4, JavaScript will only evaluate HiddenFor once you've paused to inspect it

Struggling with evaluating a hidden field in JavaScript (ASP MVC4). I've set up a model in my View with a hidden input for one of the properties. @Html.HiddenFor(mdl => mdl.FilterByUser, new { @id = "filterByUserId" }) Within my Helper, I have a ...

React component is unable to identify prop

I'm attempting to send an array of objects from the main App.js file to a smaller component using props. However, for some reason, the prop is not being recognized within the smaller component file. https://i.stack.imgur.com/WuyFr.png https://i.stac ...

Adding a border in jQuery or Javascript to highlight empty form fields

After making the decision to dive into the world of Javascript, I've been dedicated to perfecting a script that will encase empty elements with a border right before the user submits a form. My ultimate goal is to implement live validation in the form ...

Challenges in retrieving information from a two-dimensional JSON dataset

I am encountering an issue with a nested JSON structure. JSON: [{"id":"15", "rand_key":"", "landlord_name":"Shah", "property_req_1":{ "lead_req_id":"", "lead_id":"0", "category_id":"1", "region_id":"1", "area_location_id":"17", ...

Remove class names from CSS and store them in an array

I have a specific HTML file where the CSS is included at the beginning of the document, enclosed within comment tags. My task is to extract the names of the classes located between these comment tags. /* target >> */ .oneClass { ... } .anotherOne { ...

Is there a way to add pins to separate entity layers, and then remove them from a specific entity layer using Bing Maps AJAX Control, Version 7.0?

Currently, I am utilizing Bing Maps to display store locations on a map. The information about the stores is coming from a dynamic JSON response. When the page loads, the map shows local stores with pushpins and infoboxes. As the map pans, my goal is to re ...

Discovering objects on a JavaScript webpage using Selenium

Looking to automate some searches for myself, but running into an issue. Here is the website in question: Struggling to locate the search bar using the program, and unsure why. driver = webdriver.Firefox() driver.get('https://shop.orgatop.de/') ...

mongodb $lookup allows for referencing multiple documents from an embedded array

My database consists of collections for boards, lists, and cards. Each board document contains an array of lists and I am working towards achieving the following desired output: { _id: 1, title: "a board", lists: [ { _i ...

Transforming a canvas into a div element

Hey there, I'm looking to swap out one canvas for another but I'm not sure how it will look on the browser. Any help would be greatly appreciated. <div id="juego"> <canvas width="203" height="256" id="1" class="bloque"></canvas& ...