Exploring the depths of JSON: Unraveling the secrets of reading dynamic object data

Currently, I am receiving a JSON file from another app and my goal is to parse it in order to extract the data contained within. The JSON includes user-defined dynamic data with changing key/value pairs, which has left me feeling uncertain about how to effectively process these variables for further use.

Below is an example of the JSON structure that I need to work with:

{
  "context": [
    {
      "one": "https://example.one.com"
    },
    {
      "two": "https://example.two.com"
    },
    {
      "three": "https://example.three.com"
    }
  ],
  "name": "Batman",
  "age": "30",
  "one:myField": {
    "two:myField2": "Hello"
  },
  "three:myField3": "Hello2"
}

While I can easily access static or well-defined data like name & age, my challenge lies in understanding how to retrieve user-defined/dynamic data from this JSON format where key/value pairs are not consistent and may not follow a specific order after the 'age' property.

I am currently exploring ways to extract all user-defined data from this JSON:

  "one:myField": {
    "two:myField2": "Hello"
  },
  "three:myField3": "Hello2"

Is there a straightforward method or library that can help achieve this task? I am building my application using Vuejs/Nuxtjs framework.

Answer №1

I believe the API you are currently utilizing may not be the most optimal choice. It would be beneficial to have constant object parameters that provide a consistent way to access information. If you encounter unknown parameters, consider parsing JSON into an object and iterating through it.

const object = { a: 1, b: 2, c: 3 };

for (const property in object) {
  console.log(`${property}: ${object[property]}`);
}

Answer №2

To achieve this, you can loop through the keys of an object using Object.keys().

Here is a demonstration :

const data = {
  "context": [
    {
      "one": "https://example.one.com"
    },
    {
      "two": "https://example.two.com"
    },
    {
      "three": "https://example.three.com"
    }
  ],
  "name": "Superman",
  "age": "35",
  "power:myField": {
    "strength:myField2": "Hi"
  },
  "hero:myField3": "Greetings"
};

Object.keys(data).forEach(key => {
    if (typeof data[key] === 'object') {
    Object.keys(data[key]).forEach(innerKey => {
        console.log(innerKey, data[key][innerKey])
    })
  } else {
     console.log(key, data[key])
  }
})

Answer №3

By utilizing the powerful combination of Object.keys and a recursive function, you can seamlessly handle multiple nested objects in your code without the need for constant refactoring!

const jsonData = {
    context: [
        {
            one: "https://example.one.com",
        },
        {
            two: "https://example.two.com",
        },
        {
            three: "https://example.three.com",
        },
    ],
    name: "Batman",
    age: "30",
    "one:myField": {
        "two:myField2": "Hello",
        "one_nested:myField": {
            another_nested_key: "another_nested_value",
        },
    },
    "three:myField3": "Hello2",
};

recursive(jsonData);

function recursive(nestedKey) {
    if (typeof nestedKey !== "object") return;

    Object.keys(nestedKey).forEach((key) => {
        if (typeof nestedKey[key] === "object") {
            recursive(nestedKey[key]);
        } else {
            console.log(key, nestedKey[key]);

            // add your conditions here

            if (key === "name") {
                // bla bla bla
            }
        }
    });
}

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

Troubleshooting problems with data rendering in jQuery

Currently, my goal is to use JQuery to display a menu of checkboxes based on a specific template in a div. To enhance user experience, I have included a search box that will filter the menu items. However, there is an unusual issue occurring. When the men ...

retrieve the data-task-IDs from the rows within the table

I am currently working with a table that looks like this: <table id="tblTasks"> <thead> <tr> <th>Name</th> <th>Due</th> ...

Creating interactive routes and pages using Next.js and Prisma, embracing dynamic functionality

I have product information cards stored in my database, and I successfully display them on the user's page. Now, I want to add a "More Details" button on each card that will link to a new page (/pages/card/[id]). However, I'm unsure how to retrie ...

Tips for organizing dynamic table data following an append operation

Hey there! I'm currently working on a project involving sorting students after applying filters. Once the students have been filtered, I need to append classes and text to buttons as shown in the image below: https://i.stack.imgur.com/c9Mtm.png The HT ...

Converting an object to JSON without prior knowledge of its type

Currently, I have a small program that consists of two classes. One class serves as the entry point of my application and deals with commandline arguments upon startup, while the other class contains options that I need to serialize into JSON format for la ...

Issue with ESLint: Unexpected token found in JavaScript when converting to a dictionary

I've implemented a JavaScript code snippet that loops through an array of fields to find specific properties and then adds them to a dictionary. For another example, you can check out this site. return this.getFields() .reduce((mappings, field) =& ...

execute javascript code after loading ajax content

Although this question may have been asked before, I am completely unfamiliar with the subject and unable to apply the existing answers. Despite following tutorials for every script on my page, I have encountered a problem. Specifically, I have a section w ...

Rails does not transfer data-attributes in HTML5

I have a layout set up to show users: %table.table %tbody - @users.each do |user| %tr %td= avatar_tag user, {small:true, rounded:true} %td = username user .online-tag = user.online? %td= ...

Node.js Express application: Managing endpoint conflicts

After searching for a solution to this issue and not finding one, I apologize if this question is repetitive. In my express+node.js application, I have two endpoints defined as follows: // Retrieves a tweet by unique id app.get('/tweets:id', fu ...

Tips for altering an element's style attribute using ERB and JQuery while including a % symbol within the value

I'm attempting to adjust the style="width: 5%" attribute of a span using Jquery and AJAX. This width needs to be specified in percentage as it represents a progress bar. Here is my code snippet from html.erb: <div class="progress success round" ...

Error: 'error' is undefined

Error Alert: The code is encountering a ReferenceError, indicating that 'error' is not defined in the following snippet: app.post('/register', function(req, res) { var hash = bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(10)) ...

Is there a way to retrieve the io object within the io.sockets.on callback function?

My preference is to not alter my sockets method. I was hoping to be able to utilize the io object within the connected function. Could this be a possibility? function sockets (server) { const io = require('socket.io')(server); io.sockets.on ...

Enhancing socket.io with the incorporation of a variable

I was looking for a way to connect an object named player to various sockets. My initial approach was to simply do socket.prototype.player = whatever; However, no matter what I attempt to prototype, it always returns undefined. Does anyone have a solution ...

Customize Cell Styling with Bootstrap Full Calendar CSS

I am attempting to implement a Bootstrap calendar feature where cells are colored green if the timestamp is greater than today's date. This can be achieved by: $checkTime > $today cell.css = green background I came across this code snippet on St ...

Managing JSON data retrieval and manipulation techniques

My code is set up to display the image, title, and summary for all entries in a JSON file. However, I only want to display the image, title, and summary for the first entry, and only show the title for the rest of the entries. Please advise. <html> ...

What is the best way to make an AJAX request to retrieve data from a database in JSP using Extjs?

Currently, I am utilizing the Extjs framework and have created a servlet to retrieve data from a database. Once the data is retrieved, it is stored in a list and then converted into a JSON array. I am now looking to incorporate this data into a JSP page us ...

Tips for resolving the issue of 'defineExpose' method being undefined in Vue3

Struggling to pass a method from child to parent; unfortunately, the defineExpose() method seems to be malfunctioning. Could anyone provide guidance on what might be going wrong? For additional context, feel free to check out my previous question <scri ...

Ensure the video fills the entire width of its parent element and adjusts its height accordingly to maintain a 16:9

I am looking to make both videos fill 100% width of their parent element while keeping their aspect ratio intact. The parent element takes up 50% of the window's width, so the videos need to be responsive. I have come across numerous solutions that ...

Setting up ckeditor5 in Nuxt the right way

Recently, I encountered the CkEditor5 setting in Nuxt js for the first time and found it to be quite confusing with plenty of errors surfacing. I attempted to customize my version of ckeditor5 in nuxt.js by following this guide However, none of it seems ...

The evaluation of CKEDITOR's execution code

Every time I input my content into CKEDITOR, I receive the following error: "Unexpected token < " This is the code I am using: eval('CKEDITOR.instances.'+ckeditorID+'.insertHtml('+text+')'); The content of variable text ...