Is it possible for a JSON array to consist of objects with varying key/value pairs?

Is it possible for a JSON array to contain objects with different key/value pairs? The example provided in this tutorial shows objects within the JSON array having the same key/value pair:

{
  "example": [
    {
      "firstName": "John",
      "lastName": "Doe"
    },
    {
      "firstName": "Anna",
      "lastName": "Smith"
    },
    {
      "firstName": "Peter",
      "lastName": "Jones"
    }
  ]
}

If I wanted to change this and have objects with different key/value pairs inside the JSON array, would the following still be considered valid JSON?

{
  "example": [
    {
      "firstName": "John",
      "lastName": "Doe"
    },
    {
      "fruit": "apple"
    },
    {
      "length": 100,
      "width": 60,
      "height": 30
    }
  ]
}

I just want to confirm if this is acceptable. If so, how can I use JavaScript to determine whether the JSON "example" field contains homogeneous objects (like the first set) or heterogeneous objects (like the second set)?

Answer №1

Feel free to utilize any structure of your choosing. JSON does not adhere to a schema like XML, and JavaScript is dynamically typed.

To convert your JSON into a JavaScript object, you can use JSON.parse and then check if the property exists.

var obj = JSON.parse(jsonString);
if(typeof obj.example[0].firstName !== "undefined") {
   //perform an action
}

Answer №2

Feel free to combine and experiment with different elements.

Why not give it a try?

Check if someItem.example is defined:
typeof someItem.example !== 'undefined' // Returns true

Answer №3

This JSON format is completely valid. In my personal opinion, I find this syntax to be more readable:

{
    "example": [
        {
            "firstName": "Jane",
            "lastName": "Smith"
        },
        {
            "animal": "dog"
        },
        {
            "length": 50,
            "width": 40,
            "height": 20
        }
    ]
}

Regarding your second query, you can extract data from a JSON string using

var result = JSON.parse(jsonString);
. You can then access the data by calling result.property.subproperty. Variables in JSON can take the form of objects, arrays, strings, or numbers, allowing for complex nested structures.

Answer №4

Feel empowered to manipulate the contents of the array as you see fit. Just keep in mind this important reminder before attempting to access properties of each item within your array.

Keep in mind that you will only be able to deserialize this into an array of objects on your server side, so don't be caught off guard later on.

Here's a helpful tip: consider including a common field in the objects that specifies their "type," making it easier for processing down the line.

var array = [{"type":"fruit", "color":"red"},
{"type":"dog", "name":"Harry"}];

var parser = {
    fruit:function(f){
   console.log("fruit:" + f.color);
    },
    dog: function(d){
    console.log("dog:"+d.name);
    }};

for(var i=0;i<array.length;i++){
    parser[array[i].type](array[i]);
}

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

Maintaining the order of subscribers during asynchronous operations can be achieved by implementing proper synchronization

In my Angular setup, there is a component that tracks changes in its route parameters. Whenever the params change, it extracts the ID and triggers a function to fetch the corresponding record using a promise. Once the promise resolves, the component update ...

How can you achieve three layers of nested quotes in Dynamic HTML?

Working on an app that utilizes JQuery and JQTouch for iOS. The issue I'm facing involves dynamically generated HTML lists where the user clicks a row that needs to be highlighted. However, achieving this has proven tricky due to nesting 3 sets of quo ...

Avoiding unnecessary DOM updates in VueJS

Implementing an animated carousel has been my latest project, and I've been using code similar to the following: <template> <div v-for="(slides, id)" v-if="id > middle_id - 2 || id < middle_id + 2"> <div :class ...

Discovering the right row to input the data and successfully integrating it: What is the best

Below is the code I am using to add a new task: <fieldset> <legend>Create New Task</legend> <input type="text" ng-model="subtaskname" placeholder="Subtask Name" ><br /> <select id="s1" ng-model="selectedItem" ng-options=" ...

Displaying Photo on Webpage using Bearer Authorization Token in JavaScript

In my JavaScript code, I am currently loading an image using the following method: var img = new Image(); img.onload = function () { .. }; img.src = src; However, I have recently realized that I need to secure the images on my server side with OAuth 2, j ...

What is the most effective way to create a live preview using AngularJS and CSS?

Is there a way to dynamically change the background color of the body based on the hexadecimal value entered in a textfield, without using jQuery? I want the change to happen live as the user types. The current code works but it doesn't feel right. I ...

Experience the power of Kendo UI Date Picker combined with AngularJS. When the datepicker is initialized, it starts

Check out my code snippet below: When the datepicker loads initially, it appears empty. However, if you remove ng-model from the directive template, the datepicker displays its initial value correctly. Yet, changing the selected date does not mark the fo ...

"Webpack error: Including a comma within a string leads to a syntax problem when bund

I'm attempting to merge this file into my main JS. var constants = { height: 600, width: 400, default_bezier = "[ { \"startPoint\" : [51.6503017608354,203.464445873753], \"endPoint\" : [-52.41285540263849,202.372456432 ...

Execute action based on local state when component is unmounted in React

I have encountered an issue with a component's internal state not being properly propagated throughout the application, specifically under certain events. const FunComponent = (initialDescription, onSave) => { const [description, setDescription] ...

What is the solution for resolving an Optional chaining Error in a React project?

Currently, I am delving into the world of react redux while simultaneously constructing an app. One interesting aspect that caught my attention is optional chaining in user authentication. However, this method seems to be throwing an error message. You may ...

Leveraging the power of AJAX with either jquery or plain javascript to parse nested JSON data and display the

Similar Question: jquery reading nested json I am seeking a reliable method to iterate through multiple sets of data stored in JSON, some of which may have deep levels of nesting. My goal is to display this data in a table format. I am uncertain abou ...

Strange behavior of the .hasOwnProperty method

When attempting to instantiate Typescript objects from JSON data received over HTTP, I began considering using the for..in loop along with .hasOwnProperty(): class User { private name: string; private age: number; constructor(data: JSON) { ...

Encountering difficulties reaching $refs within component method

Trying to access a ref defined within a template when an element is clicked. Here's the HTML: <!DOCTYPE html> <html lang="en"> <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protectio ...

Is there a way to activate a Superfish jQuery Menu with a click instead of a hover?

After doing some research on the internet, I came across an implementation of Superfish menu by Joel Birch that functions based on onclick instead of hover. I found a link on Github by Karl Swedberg which seems to be what I need. https://gist.github.com/ ...

What is the best way to insert an iframe using getElementById?

I am looking to make some changes in the JavaScript code below by removing the image logo.png lines and replacing them with iframe code. currentRoomId = document.getElementById('roomID').value; if ( document.getElementById('room_' + c ...

Getting an out-of-range exception (System.ArgumentOutOfRangeException) in C# Razor pages while attempting an AJAX call

I have a razor page model that contains a get-method. public IActionResult OnGetDuration([FromBody]int id) { Subject subject = _service.GetSubjectById(id); int duration = subject.LessonsPerWeek; return new JsonResult('a&apo ...

Is it better to have Angular and Laravel as separate applications or should Laravel serve the Angular app?

I have a new project in the works, aiming to create a large SAAS application. Although I come from a CakePHP background, I've decided to use Laravel and Angular for this venture. As I navigate through unfamiliar territory with these technologies, I a ...

Passing an array to web service as parameters using Swift

I've been struggling to send an array object to a web service. Whenever I attempt to add the array to parameters, it throws an error. Despite trying various methods, none have proved to be effective. The goal is to include ("assignees" : newList) in ...

Covering the entire screen, the Div element takes up the entirety of

Just like with other pages, the main div always takes up the entire screen visible to the user. As they scroll down, another div becomes visible: example1 , example2 Regardless of the screen size, the main div will always fill the space visible to the use ...

React Context - Ensure synchronized deletion of user posts across routes while maintaining pagination during fetching

INTRODUCTION I am striving to replicate the behavior commonly seen in social networks, where deleting a post by a user results in its automatic removal across all app routes. This functionality is reminiscent of how platforms like Instagram or TikTok oper ...