Exploring JSON data in JavaScript

In my Json data, I have a nested structure of folders and files. My goal is to determine the number of files in a specific folder and its sub-folders based on the folder's ID. Below is an example of the JSON dataset:

var jsonStr = {
    "hierarchy": {
        "date": "2014/09/24 15:21:23",
        "folder": {
            "name": "Root",
            "id": "Root",
            "file": [{
                "id": "22U2621210__PIN_検査報告書Ver1.0_20140923162232.xls"
            }, {
                "id": "C22-1(EU仕様)_20140923162409.xlsx"
            }, {
                "id": "Machine_Inspection_20140923162329.xlsx"
            }],
            "folder": {
                "name": "Level-1",
                "id": "1411396172645",
                "file": {
                    "id": "22U2621210__PIN_検査報告書Ver1.0_20140923162232.xls"
                },
                "folder": {
                    "name": "123",
                    "id": "1411538469568",
                    "file": [{
                        "id": "C22-1(EU仕様)_20140923162409.xlsx"
                    }, {
                        "id": "Machine_Inspection_20140923162329.xlsx"
                    }]
                }
            }
        }
    }
};

Each folder has a unique name and ID. If I want to find the number of files within a specific folder and its subfolders by searching with its ID, for instance, if I input the folder "name 123" and ID "1411538469568", it should display only 2 files:

"C22-1(EU仕様)_20140923162409.xlsx"
and
"Machine_Inspection_20140923162329.xlsx"
. However, if I provide the folder name "Root" and ID "Root," it should retrieve all file IDs.

I am currently working on this functionality in a JSFiddle: http://jsfiddle.net/ma3kno2o/

Answer №1

If you're looking to enhance your search capabilities, consider using Defiant.js

Have a look at this Fiddle for a specific search scenario where you can extract file IDs from the element with ID: root and Name: root:. I've used Defiant.js in this demonstration:

http://jsfiddle.net/3z8mqr3u/1/

When compared to custom search methods mentioned before, Defiant.js stands out as it simplifies the process of fetching file IDs with just one line of code:

var ids = JSON.search(json,  "//*[name = 'Root' and id = 'Root']/file/id");

This approach minimizes errors when dealing with dynamic data. Defiant.js makes use of XPath expressions for searching. Explore more about it here:

Here are some alternative options worth considering:

  1. You can utilize plain JQuery for your searches

    How to search JSON tree with jQuery

  2. Another option is JsonPath, similar to XPath but tailored for JSON files. It enables queries such as:

    $..folder.file
    

    https://code.google.com/p/jsonpath/

    https://github.com/s3u/JSONPath

  3. Consider exploring Json-Query which introduces its own language designed for deep queries. For example:

    var data = { grouped_people: { 'friends': [ {name: 'Steve', country: 'NZ'}, {name: 'Bob', country: 'US'} ], 'enemies': [ {name: 'Evil Steve', country: 'AU'} ] } }

    jsonQuery('grouped_people[][country=NZ]', {data: data})
    

    https://github.com/mmckegg/json-query

If none of these options resonate with you, there are plenty more alternatives available: Is there a query language for JSON?

Answer №2

This solution may not be the most elegant (apologies, it's 4am), but it tackles the problem through recursion. Your existing structure does not easily cater to same-level folders, so I made some adjustments and provided the corresponding code: http://jsfiddle.net/ma3kno2o/5/

function getFiles(id)
{
 var files = searchFolders(jsonStr.hierarchy.folders, false);
 alert('Found ' + files.length + " files\n" + JSON.stringify(files));

 function searchFolders(tree, count_files)
 {
    var data = [];     
    $.each(tree, function(key, val) {        
        var into = !count_files ? val.id == id : count_files;

        if (val.files && into)
            $.merge(data, getFiles(val.files));

        if (val.folders)
            $.merge(data, searchFolders(val.folders, into));                  

    });
    return data;
 }

 function getFiles(tree)
 { 
    var files = [];
    if (tree.id) return [tree.id]; 
    $.each(tree, function(key,val) {
       if (val.id)
          files.push(val.id);
    });
    return files;
 };
}


var jsonStr = {
    "hierarchy": {
        "date": "2014/09/24 15:21:23",
        "folders": [{
            "name": "Root",
            "id": "Root",
            "files": [{
                "id": "file.1"
            }, {
                "id": "file.2"
            }, {
                "id": "file.3"
            }],
            "folders": [{
                "name": "Level-1",
                "id": "1411396172645",
                "files": {
                    "id": "file.4"
                },
                "folders": [{
                    "name": "123",
                    "id": "1411538469568",
                    "files": [{
                        "id": "file.5"
                    }, {
                        "id": "file.6"
                    }]},
                    {
                    "name": "123",
                    "id": "1411538469569",
                    "files": [{
                        "id": "file.7"
                    }, {
                        "id": "file.8"
                    }]
                }]
            }]
        }]
    }
};

The initial code needed modifications for your new requirements.

http://jsfiddle.net/ma3kno2o/8/

function getFiles(id)
{
 var stp = -1;
 var files = searchFolders(jsonStr.hierarchy, false);
 alert('Found ' + files.length + " files\n" + JSON.stringify(files));

 function searchFolders(tree, count_files)
 {
     var data = [];  
     var folders = tree.folder.length > 1 ? tree.folder : [tree.folder];
     $.each(folders, function(key, val) {  
        var into = !count_files ? val.id == id : count_files;

         if (val.file && into)
            $.merge(data, getFiles(val.file));

         if (val.folder)
            $.merge(data, searchFolders(val, into));  
    });
    return data;
 }

 function getFiles(tree)
 { 
    var files = [];
    if (tree.id) return [tree.id]; 
    $.each(tree, function(key,val) {
       if (val.id)
          files.push(val.id);
    });
    return files;
 };
}


var jsonStr= {"hierarchy":{"date":"2014/09/24 18:13:00","folder":{"name":"Root","id":"Root","file":[{"id":"file.1"},{"id":"file.2"},{"id":"file.3"}],"folder":[{"name":"Level-1","id":"1411396172645","file":{"id":"file.4"},"folder":{"name":"123","id":"1411538469568","file":[{"id":"file.5"},{"id":"file.6"}],"folder":{"name":"123-a","id":"1411549962260","file":{"id":"file.7"}}}},{"name":"level-2","id":"1411549976987","file":{"id":"file.8"}}]}}};

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

Retrieving precise information from a Json file with PHP

Hey there, I have a JSON file and I'm looking to extract certain data from it. Here's how the file appears: { "took" : 1, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 }, ...

Automatically submitting Ajax form upon loading the page

I am attempting to use ajax to automatically submit a form to a database upon page load. The form and php code work perfectly when manually submitted, but for some reason, the ajax function does not trigger. Despite checking the console for errors and con ...

Is there a way to automate the loading process when a file is uploaded to an HTML input field?

How can I upload a file via Ajax post in HTML without clicking the button? Currently, my code only works after clicking the bootstrap button. My current implementation is as follows: $(document).ready(function () { $("#but_upload").click(function () { ...

Mongoose schema nesting guide

I've encountered an issue while attempting to nest schemas in mongoose, and unfortunately I'm struggling to pinpoint the exact cause. Here's what my current setup looks like. Starting with the parent schema: const Comment = require("./Comm ...

Guide to dynamically displaying different URLs based on checkbox selection using Ajax

My goal is to dynamically change the view of a page based on which checkbox is checked. Additionally, I want to ensure that when one checkbox is selected, another becomes unchecked. <input class="searchType" type="checkbox"></input> <input ...

Using jQuery's .remove() function removes all of the children from the container, rather than just one at

For my latest project, I am focused on creating a seamless full-page transition using AJAX calls. The challenge I'm facing is removing content from the DOM when loading in a new page. Despite adding a unique class or ID to the element, the .remove() f ...

Tips for incorporating a Font Awesome icon <i> within a select dropdown and customizing its appearance

I am facing an issue while trying to insert an icon into a select option. The error message I received is: Warning: validateDOMNesting(...): cannot appear as a child of <option> To indicate that certain fields are required, I am using asterisk ic ...

Field must have a base type specified to proceed

Currently, I am in the process of developing a discord.js bot. The structure I have set up involves a folder that contains all the commands, and when a command is called, index.js directs it to the appropriate file. However, when attempting to run the bot, ...

In order to successfully utilize Node.js, Async.js, and Listeners, one must ensure

Here is the log output from the code below, I am unsure why it is throwing an error. It seems that the numbers at the end of each line represent line number:char number. I will highlight some important line numbers within the code. Having trouble with t ...

Ways to troubleshoot and verify values in PHP that are sent through AJAX

In my jQuery function, I am using AJAX to send values to a PHP file: $.ajax({ //make ajax request to cart_process.php url: "cart_process.php", type: "POST", dataType: "json", //expect json value from server data: { quantity: iqty, ...

Tips for validating a session on a React client following a successful authentication via an Express session

After setting up an express REST API backend and React Front End, the front end app redirects users to the signin page using OAuth. The express server then creates a session ID after successful authentication, which can be seen as a browser cookie connect. ...

What is the best way to retrieve the initial word from a JSON dictionary?

When working with JSON data and aiming to convert it into an Excel format, my goal is to arrange dictionary content in a tabular form in Excel. **Code** f = open(filename, 'r') #open json file data = json.loads(f.read()) #load js ...

A bot responsible for assigning roles never fails to remove a role when necessary

My goal was to develop a bot that automatically assigns users a role based on the language they speak in a bilingual server. However, when I tried to assign myself the Czech role, it added the role but failed to remove the rest: const Discord = require(&a ...

Is there a way to transform a dynamically created JavaScript table into JSON or XML format and then store it as a file?

A dynamic table of properties is created in JavaScript using a function: // update table PropertyWindow.prototype._update = function (text) { if (text === void 0) { text = "&lt;no properties to display&gt;"; } this._propertyWindow.html(text); ...

perform one task following the completion of another

Can I run the second function after the first one without using a timeout event in this JavaScript code: if (direction !== "leftnav") { // DO THINGS }; setTimeout(function () { //DO OTHER THINGS AFTER THE FIRST THING }, 1000); Your input is greatly app ...

Generating data within an express route (with the use of socket.io-client)

Recently, I made the decision to refactor my code in order to separate the front and back end, which were previously combined into one service. However, I am now facing an issue where I need the web server to emit data to the data server after validation. ...

Reading a file in pyspark that contains a mix of JSON and non-JSON columns

Currently, I am faced with the task of reading and converting a csv file that contains both json and non-json columns. After successfully reading the file and storing it in a dataframe, the schema appears as follows: root |-- 'id': string (null ...

Utilizing JSON Files with C++ Programming

Currently, I am attempting to parse a JSON file using the jsoncpp library. Nevertheless, I am finding it challenging to comprehend its documentation. Can someone simplify and explain its functionality in layman's terms for me? Let's consider a s ...

Accessing information via a PHP script with the help of AJAX and jQuery

In the process of developing a gallery feature that displays a full image in a tooltip when hovering over thumbnails, I encountered an issue where the full images extended beyond the viewfinder. To address this, I decided to adjust the tooltip position bas ...

Remove a particular item by clicking on the icon in React.js

I'm currently working on a React JS exercise for creating a "To Do List". I am facing an issue where I want to delete individual tasks by clicking the trash icon, but my current code deletes all tasks at once. Can someone help me understand how to ach ...