Tips for verifying if a JSON value is an array without prior knowledge of the key

Is it possible to determine if a value in a JSON key's value is an array without prior knowledge of the key's name? There are two potential formats for the JSON object:

{
    "person": [{
            "id": "1",
            "x": "abc",
            "attributes": ["something"]
        },
        {
            "id": "1",
            "x": "abc"
        }
    ]
}

In order to parse this data effectively, I need to be able to detect whether the value of the key is an Array or just a singular value. This needs to be done without knowing the specific name of the key (for example, "attributes" in the provided code snippet). The challenge also lies in looping through all "person" objects and their respective keys.

I have come across a solution that works when the key name is known and there is only one "person" object. However, I am unsure of how to adapt this approach when dealing with multiple "person" objects and not knowing the key names.

if (Array.isArray(json.person['attributes'])) // assuming json holds the parsed JSON content
    {

    } 

Answer №1

If you're looking to check for Array values in a data payload, consider the following approach:

Here is the data payload structure:

const payload = {
    person: [
        {
            id: 1,
            x: 'abc',
            attributes: ['something']
        },
        {
            id: 1,
            x: 'abc'
        }
    ]
};

This function can help identify entries with Array values:

const arrayEntries = jsonData => {

    let result = [{
        isArray: false,
        jsonKey: null,
        jsonValue: null
    }];

    Object.entries(jsonData).map(entry => {
        if (Array.isArray(entry[1])) {
            result.push({
                isArray: true,
                jsonKey: entry[0],
                jsonValue: entry[1]
            });
        }
    });

    return result;
}

Example of how to use this function:

payload.person.map(person => {
    console.log(arrayEntries(person));
});

The output will resemble this format.

For further reference and demonstration, visit: https://codepen.io/WIS-Graphics/pen/ExjVPEz


ES5 Version:

function arrayEntries(json) {

    var response = [{
        isArray: false,
        jsonKey: null,
        jsonValue: null
    }];

    Object.entries(json).map(function(entry) {
        if (Array.isArray(entry[1])) {
            response.push({
                isArray: true,
                jsonKey: entry[0],
                jsonValue: entry[1]
            });
        }
    });

    return response;
}

payload.person.map(function(person) {
    console.log(arrayEntries(person));
});

https://i.sstatic.net/2VcyG.png

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

Adding firebase analytics to your NextJS app in the right way

My react/nextjs app includes a firebase.js file that looks like this: import firebase from 'firebase/app' import 'firebase/auth' import 'firebase/analytics' import 'firebase/firestore' const firebaseConfig = { api ...

What is the best way to activate an event using jQuery?

Currently, I am developing a web page where a modal window should open upon the user clicking on a specific radio button. To achieve this functionality through my jQuery code, I am trying to simulate the action of the user clicking on the radio button by: ...

jQuery wordpress Error: $ function is undefined and not recognized

Having trouble using jQuery to disable checkboxes after selecting two options on a restaurant menu displayed in a modal. Despite trying various recommendations, I have not been successful in resolving this issue. Visit the URL for reference: Here is the ...

Encountered a problem during the installation of tensorflowjs for node | Received an error: Command failed: node-pre-gyp install

While attempting to install @tensorflow/tfjs-node, I encountered the following error: Command failed: node-pre-gyp install --fallback-to-build. Is there a solution to resolve this issue? Below is the complete log: npm ERR! code 1 npm ERR! path E:\ ...

React project automatically refreshing when local server generates new files

I have developed a tool for developers that allows them to retrieve device data from a database for a specific time period, generate plots using matplotlib, save the plots locally, and display them on a webpage. The frontend is built using create-react-app ...

Identifying and Blocking Users from Accessing External Domains Outside of the Angular Application

I am working on an angular application and I need to implement a feature where I can detect when a user navigates outside of the app domain from a specific component. For instance, let's say the user is on the upload component processing important in ...

Refresh ng-repeat following data entry or push in Angular Material dialog

Currently, I am facing an issue with adding a new object to an ng-repeat array. The array is populated with data fetched through an $http request. My goal is to input data in a dialog and pass it to a function that will then add the data as an object to th ...

How to incorporate an image within a div element without reliance on the <img> tag

I am dealing with HTML content <div> <img src="xyz.jpg"> </div> The challenge I am facing is fetching an image in hex format from a web service, converting it to JPEG, and displaying it inside a div. However, the <img src=""> ta ...

Guide on loading numerous JavaScript files into a database using the mongo shell

I am faced with the task of loading multiple js files that contain collections creations and seeds into my database using the mongo command. Currently, I have been manually loading data from each file one by one like so: mongo <host>:<port>/< ...

Increase the call stack of a failed test beyond the helper function and up to the test case

As I was writing unit tests for my codebase, I noticed that I kept duplicating the code responsible for making HTTP requests and setting expectations for the response. To avoid this redundancy, I created some helper functions, one of which is called expect ...

Unable to retrieve file paths for assets using Node.js Server and Three.js

I am facing challenges when it comes to loading 3D models from a folder on my computer using a localhost node.js test server with the three.js library. Below is my app.js file that I execute via command line in the project directory using the 'node a ...

I am in the process of transforming my basic JS Array into one that contains key/value

Currently, I am utilizing jQuery to create an Array in the following manner: var arr = new Array(); $('#some-form .some-input').each(function() { arr.push($(this).val()); ...

Searching for the position of a substring in every element of the array using the "strpos"

Is there a way in PHP to determine if a specific string is contained within an array value, even if it's not the exact array value? $array = array( 0 => 'blue', 1 => 'red', 2 => 'green', ...

Enhancing JavaScript Variables Through Dynamic Ajax/PHP Interaction

I've been encountering some difficulties when trying to refresh my game. Initially, I attempted echoing the entire script each time... but that method was not aesthetically pleasing. Currently, I am experimenting with updating the variables through an ...

Clicking on an Angular routerLink that points to the current route does not function unless the page is re

Currently, I am working on an E-commerce project. In the shop page, when a user clicks on the "View More" button for a product, I redirect them to the product details page with the specific product id. <a [routerLink]="['/product-details' ...

Retain only N instances of a particular character within a JavaScript string

Suppose I have a string like this: "a_b_c_d_restofthestring" and I want to keep only 2 underscores. For example, "a_b_cdrestofthestring" "abc_d_restofthestring" Both of these are valid outputs. This is my current implementation: let str = "___sdaj_ ...

A Guide to Filtering MongoDB Data Using Array Values

I am trying to extract specific data from a document in my collection that contains values stored in an array. { "name": "ABC", "details": [ {"color": "red", "price": 20000}, {" ...

Retrieving the variable value instead of a reference using Ajax in ASP

After spending nearly two days trying to figure out this code and researching every possible solution, I still haven't been able to get it to work properly. It's likely that I'm implementing it incorrectly or missing something, so I've ...

How can I store the output of Javascript in a PHP variable?

<script> FB.api('/me', function(user) { if(user != null) { var name = document.getElementById('uid'); uid.innerHTML = user.uid } }); </script> U ...

Guide on parsing logs containing JSON objects utilizing Fluentd

In my nginx log file, I come across lines like this: 127.0.0.1 192.168.0.1 - [28/Feb/2013:12:00:00 +0900] "GET / HTTP/1.1" 200 777 "-" "Opera/12.0" - <{"key1":"value1","key2":98765,"key3":false,"key4":["one","two"],"key5":{"key22":98765,"key23":false,"k ...