Parsing JSON data with JavaScript

I'm currently working with this JSON data, attempting to extract all the keys and values. The challenge I'm facing is that some of these keys contain inner objects with additional key-value pairs.

Is it possible to achieve this recursively using JavaScript exclusively? What am I overlooking?

{
  "@xmlns:v6": "urn://oracle.bi.webservices/v6",
  "v6:pageID": "?",
  "v6:reportID": "?",
  "v6:report": {
    "v6:reportPath": "?",
    "v6:reportXml": "?"
  },
  "v6:reportViewName": "?",
  "v6:reportParams": {
    "comment": [
      "Zero or more repetitions: ",
      "Zero or more repetitions: ",
      "Zero or more repetitions: ",
      "Zero or more repetitions: ",
      "Optional: "
    ],
    "v6:filterExpressions": "?",
    "v6:variables": {
      "v6:name": "?",
      "v6:value": "?"
    },
    "v6:nameValues": {
      "v6:name": "?",
      "v6:value": "?"
    },
    "v6:templateInfos": {
      "v6:templateForEach": "?",
      "v6:templateIterator": "?",
      "comment": "Zero or more repetitions: ",
      "v6:instance": {
        "v6:instanceName": "?",
        "comment": "Zero or more repetitions: ",
        "v6:nameValues": {
          "v6:name": "?",
          "v6:value": "?"
        }
      }
    },
    "v6:viewName": "?"
  },
  "v6:options": {
    "v6:enableDelayLoading": "?",
    "v6:linkMode": "?"
  },
  "v6:sessionID": "?"
}

It's worth mentioning the code snippet that I'm currently trying to work through:

    function parse(data,child,parent){
    var nextRept = false;
        if(child){  
        for(var i = 0; i < tmp.parents.length ; i++){
            if(tmp.parents[i].name == parent){
                if(!tmp.parents[i].children)
                    tmp.parents[i].children = [];
                var keys = Object.keys(data);
                for (var k = 0; k < keys.length; k++) {
                var val = data[keys[k]];
                if(typeof val === 'object')
                {
                 tmp.parents.push({name: keys[k].replace("v6:","")} ); //adding the parent
                 parse(val,true,keys[k].replace("v6:","")); // adding children recursively 
                }
                if(val == '?')
                { // handle valid param
                    var attr = false;
                    if(keys[k].indexOf('@') == 0){
                        attr = true;
                        keys[k] = keys[k].replace("@","");
                    }
                    tmp.parents[i].children.push({name: keys[k].replace("v6:","") , value : val , isAttr : attr , isRepet : nextRept});
                    isRepet = false;
                }
                }
                return;
            }

        }
            return;
        }

        var keys = Object.keys(data);
        for (var i = 0; i < keys.length; i++) {
            var val = data[keys[i]];
            if(typeof val === 'object')
                {
                 tmp.parents.push({name: keys[i].replace("v6:","")} ); //adding the parent
                 parse(val,true,keys[i].replace("v6:","")); // adding children recursively 
                }
                else{

                if(val.indexOf('Zero or more repetitions') != -1){
                    nextRept = true;
                    continue;
                }
                if(val == '?')
                { // handle valid param
                    var attr = false;
                    if(keys[i].indexOf('@') == 0){
                        attr = "true";
                        keys[i] = keys[i].replace("@","");
                    }
                    else{
                        attr = false;
                    }
                    tmp.parents.push({name: keys[i].replace("v6:","").replace("@","") , value : val , isAttr : attr , isRepet : nextRept});
                    isRepet = false;
                }


                }
            }

    };

Answer №1

This solution was put together quickly, but it should be effective for handling iteration through objects, arrays, and strings.

var obj = {
    "item":     "value",
    "item2":    ["value1","value2","value3"],
    "item3":    {"item3-1": ["item3-1-1", "item3-1-2", "item3-1-3"], "item3-2": {"morestuff": ["morestuff1", "morestuff2","morestuff3"]}}
}

function parseObject(obj){
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        var item    = obj[key];
        if(typeof item == 'string'){
            console.log(key + ' -> ' + obj[key]);
        }else{
            console.log(key + ' -> ');
            parseObject(item);
        }
      }
    }
}

parseObject(obj);

Output:

item -> value
item2 ->
0 -> value1
1 -> value2
2 -> value3
item3 ->
item3-1 ->
0 -> item3-1-1
1 -> item3-1-2
2 -> item3-1-3
item3-2 ->
morestuff ->
0 -> morestuff1
1 -> morestuff2
2 -> morestuff3

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

Avoid displaying the identical div through consecutive random fade-ins and fade-outs

I'm trying to make a JavaScript function that selects a random div from a list of divs, displays it for a few seconds, fades it out, and repeats this process in a loop. The issue I'm facing is that sometimes the same div is selected consecutively ...

Can a simple text and javascript be used to create a register/login "database"?

For a school project, I am working on creating a cross-browser login script without using PHP or MySQL. I want the registration process to store usernames and passwords in a plain text file, and the login process to check that file for matches. I acknowled ...

The Vue router is unable to access the store state

My Vue application is utilizing vue-router and vuex. I acquire an authentication token from my API, store it in localStorage, and then push it to the store. However, when the page refreshes, the app is unable to retrieve the token from localStorage and the ...

Storing results from iteration in Python to several callable variables

Looking for a solution in Python where items stores joined XML data from two website requests/responses: items = ET.fromstring(new) for item in list(items): url = item.find("url") endpoint = url.text ## resp = item.find("resp ...

Coverage report not generated when running jest

I need to include some functions (sum, mul, sub, div) in the test file as shown below, import {describe, expect} from "@jest/globals"; function sum(a,b) { return a+b; } const div = (a,b) => { return a/b; } const mul = (a,b) => { ...

Converting lengthy timestamp for year extraction in TypeScript

I am facing a challenge with extracting the year from a date of birth value stored as a long in an object retrieved from the backend. I am using Angular 4 (TypeScript) for the frontend and I would like to convert this long value into a Date object in order ...

Is there a way to determine if a table cell contains overflowing text compared to another cell?

https://i.sstatic.net/IYafA.png Is there a way to detect if the content of the fourth td overflows from the second td? I am looking for a method to determine which td has overflowed text and identify which td's text is overflowing. What approach ca ...

The jQuery plugin embedded in the Joomla 3.2 module fails to load or function properly

Seeking help with a JavaScript issue on my Joomla website. I'm not an expert, so please bear with me. I am using a regular plugin (not a Joomla specific one) to display my portfolio. It should work like this: ... black.html This is how it shouldn&a ...

Using Three.js to render an animated scene in a web browser

I've been working on an animation project involving an avatar moving her arms. I created the animation in Blender (v2.75) and exported it to JSON (r71). However, when I try to display it in the browser, the avatar appears but there is no movement in h ...

Transform an array containing objects for convenient manipulation

I am attempting to manipulate an array using parse, push, and save data commands, but it seems like the code is not working properly. Can anyone offer assistance? I am very new to programming and just trying to improve my skills. The array should contain ...

Building a Dynamic Control Flow Diagram with jQuery, Integrated with PHP and MySQL

I am looking to incorporate a Flow Chart feature that allows users to easily create and save flow charts using the tool. However, I have encountered some limitations with the plugin I'm currently using: http://www.jqueryscript.net/chart-graph/Simple-S ...

Displaying a sneak peek of the information along with a "See More" button beneath the title in React

My goal is to create a section header followed by preview content that defaults to showing only the first few lines. The text would then fade out, with an option to expand on click labeled "Show More." This functionality is similar to how Reddit displays p ...

Custom geometry in Three.js raycaster detects incorrect object

I am facing a challenge with the default cube's appearance in wireframe mode, as it is made up of triangles instead of squares. To combat this, I created my own geometry which looks satisfactory. However, I have noticed that the raycaster does not fu ...

Increasing a value within HTML using TypeScript in Angular

I'm working with Angular and I have a TypeScript variable initialized to 0. However, when trying to increment it using *ngFor in my .ts file, the increment is not happening (even though the loop is running correctly). my-page.html <div *ngFor=&quo ...

What's the most efficient way to create separate .zip files for multiple folders recursively?

I'm facing an issue with zipping a set of folders named *.pages. I want to create individual .zip files for each folder, like converting "example1.pages" into "example1.pages.zip," and so on, while also including the contents of the respective folders ...

Navigating File Paths in Node.js

My directory structure is as follows: Main > models > file1.ejs | |> routes > file2.ejs In my code, I'm trying to require file1 from file2 like this: const variable = require("../models/file1.ejs). But what if I don't want to ...

Testing a Component Function in ReactJS: A Step-by-Step Guide

Testing methods in a Meteor application using mocha/chai can be done like this: describe('postMessage', () => { it('should add message', (done) => { // EXECUTE const messageId = postMessage.call({ articleId: 123, conten ...

JavaScript preload with webpack ES6 import for customizable prefetching

Within a large-scale React SPA, my goal is to have certain code chunks loaded only when a user opens or utilizes specific screens or features. Many of our React components are lazily loaded using const Component=React.lazy(() => import('./lazyCode& ...

Is it possible to swap out a JSON schema for a YAML schema, or vice versa?

My device application receives data in JSON format generated by a web-based application using a YAML schema. The challenge is that my device has limited resources and can only validate JSON data against a JSON schema. Can we use a JSON schema instead of t ...

Error in Vue Vuelidate appearing when form is submitted with empty data property

I have been working on some basic validation for required fields and minimum length. The problem arises when I submit a network request for data insertion, the validation works perfectly fine. However, after the network call, if I try to make my text fie ...