Determine the number of entries in a JSON object

I am encountering an issue while trying to calculate the number of records in a JSON object, as I am getting an incorrect count.

Snippet

var jsonObject = {"d":"[{\"Country\":\"\",\"CountryCode\":\"\",\"Location\":\"\",\"Group\":\"\",\"RoomMailId\":\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="efaa978c878e81888abd808082bb8a9c9bdeaf8b8a8280c18c8082">[email protected]</a>\",\"Description\":\"\",\"Telephone\":\"\",\"DisplayName\":\"ExchangeRoomTest1\",\"CondecoRoomId\":0,\"CondecoRoomName\":\"\",\"IsMapped\":false,\"LastSyncTimeLocal\":\"\"},{\"Country\":\"\",\"CountryCode\":\"\",\"Location\":\"\",\"Group\":\"\",\"RoomMailId\":\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3f6cbd0dbd2ddd4d6e1dcdcdee7d6c0c781f3d7d6dedc9dd0dcde">[email protected]</a>\",\"Description\":\"\",\"Telephone\":\"\",\"DisplayName\":\"ExchangeRoomTest2\",\"CondecoRoomId\":0,\"CondecoRoomName\":\"\",\"IsMapped\":false,\"LastSyncTimeLocal\":\"\"}]"};
var keyCount  = Object.keys(jsonObject.d).length
document.write(keyCount);

Result

489

Expected Result

2

Answer №1

d should be utilized as a string rather than a parsed array.

var keyCount  = Object.keys(JSON.parse(jsonObject.d)).length
console.log(keyCount);

It is recommended to avoid using document.write() in modern JavaScript due to its outdated nature and lack of utility in contemporary development practices.

Answer №2

Consider utilizing JSON.parse() in place of Object.keys()

Please take note: jsonObject.d represents an Array

var jsonObject = {"d":"[{\"Country\":\"\",\"CountryCode\":\"\",\"Location\":\"\",\"Group\":\"\",\"RoomMailId\":\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="06437e656e676861635469696b52637572374662636b692865696b">[email protected]</a>\",\"Description\":\"\",\"Telephone\":\"\",\"DisplayName\":\"ExchangeRoomTest1\",\"CondecoRoomId\":0,\"CondecoRoomName\":\"\",\"IsMapped\":false,\"LastSyncTimeLocal\":\"\"},{\"Country\":\"\",\"CountryCode\":\"\",\"Location\":\"\",\"Group\":\"\",\"RoomMailId\":\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d78455e555c535a586f52525069584e490f7d59585052135e5250">[email protected]</a>\",\"Description\":\"\",\"Telephone\":\"\",\"DisplayName\":\"ExchangeRoomTest2\",\"CondecoRoomId\":0,\"CondecoRoomName\":\"\",\"IsMapped\":false,\"LastSyncTimeLocal\":\"\"}]"};

var keyCount  = JSON.parse(jsonObject.d).length

document.write(keyCount);

Answer №3

To work with stringified data, simply use the JSON.parse() method to convert it into a JavaScript object, allowing you to then access its length property.

var jsonObject = {
  "d": "[{\"Country\":\"\",\"CountryCode\":\"\",\"Location\":\"\",\"Group\":\"\",\"RoomMailId\":\"example@example.com\",\"Description\":\"\",\"Telephone\":\"\",\"DisplayName\":\"ExchangeRoomTest1\",\"CondecoRoomId\":0,\"CondecoRoomName\":\"\",\"IsMapped\":false,\"LastSyncTimeLocal\":\"\"},{\"Country\":\"\",\"CountryCode\":\"\",\"Location\":\"\",\"Group\":\"\",\"RoomMailId\":\"example2@example.com\",\"Description\":\"\",\"Telephone\":\"\",\"DisplayName\":\"ExchangeRoomTest2\",\"CondecoRoomId\":0,\"CondecoRoomName\":\"\",\"IsMapped\":false,\"LastSyncTimeLocal\":\"\"}]"
};
var keyCount = Object.keys(JSON.parse(jsonObject.d)).length;
console.log(keyCount)

Answer №4

In order to determine the number of key/value pairs in a JSON object, we must first convert it into an array. This will allow us to easily calculate the count by simply counting the elements in the array, which equates to the number of key value pairs in the JSON object.

The method Object.keys() generates an array consisting of strings that represent the enumerable properties found within the object.

function countObjectKeys(obj) { 
    return Object.keys(obj).length; 
}

//Example of Usage
var person = {"name":"Alice", "age":30};
console.log(countObjectKeys(person)); //2

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

Ignore undefined values when parsing JSON with jQuery

I am working with an API that sends back a large JSON response using AJAX. To display this data on my webpage, I use `parse.JSON` and loop through it with jQuery's `$.each` method to append the results to a DOM element. However, I have encountered iss ...

change the css back to its original state when a key is pressed

Is there a way to retrieve the original CSS of an element that changes on hover without rewriting it all? Below is my code: $(document).keydown(function(e) { if (e.keyCode == 27) { $(NBSmegamenu).css('display', 'none');} ...

Click on the window.location.href to redirect with multiple input values

I am facing a challenge with my checkboxes (from the blog label) and the code I have been using to load selected labels. However, this code seems to only work for one label. Despite multiple attempts, I have found that it only functions properly with one ...

Removing HTML tags from a string while preserving specific tags in JavaScript

Here is a JavaScript string that I am working with: var test = "<p>test</p> FOLER.PRODUCTS<12345><level-2>"; I'm trying to remove the HTML tags from the string because the service I'm using doesn't accept them. Here ...

React Weather App experiencing issues with prop communication and updating variables

My innovative weather app allows users to input custom longitude and latitude coordinates. Once the coordinates are received, they are passed as props to a child component where they are used in an API call to fetch data for that specific area. While ever ...

What is the output of the createRange() function?

I am encountering an issue with my code that is causing the highlighted text to always appear at the end of the page when it pops up. Is there a way to make it show in the middle of the line or below the selected text instead? I have included the current ...

Responsive left and right image styling in CSS and HTML

I have designed a landing page with fixed left and right images and content in the middle. It looks fine on desktop view, but on mobile view, the images are overlapping the content. How can I resolve this issue? <div class=" ...

Utilizing Javascript to share images from a public Facebook page to a user's timeline via the Facebook API

Can someone assist me with finding a way to share a photo from a public Facebook page to the user's timeline using JavaScript? Is it possible to achieve this with FB.api or FB.ui? I have successfully shared feeds to the timeline using FB.ui, but am no ...

What is the connection between serialization and JSON?

Can you explain serialization? Serialization is the process of converting an object into a stream of bytes, allowing it to be sent over a network or stored in a file. This allows the object to be reconstructed later on. What exactly is JSON? JSON stands ...

What is the reason for jQuery displaying undefined when attempting to retrieve a custom data attribute using .prop()?

In my dynamic HTML generated by JavaScript, the following code snippet is included: $(".task-status").live("click", function () { alert("data-id using prop: " + $(this).prop("data-id")) alert("data-id using data: " + $(this).data("id")) ...

Clicking on an image in a jQuery autocomplete menu will trigger a data post to an Express

My jquery autocomplete menu is functioning properly, displaying a list of books with author, title, and book image. I am now looking to enhance it by allowing users to click on the book image and then have the book title posted to an express app.post metho ...

Incorporating React-Native components into a Next.js application within an Nx monorepository: A Step-by-Step

I'm encountering an issue while attempting to integrate React Native components into an Nx monorepo setup. Initially, the Nextjs app compiles successfully: info - Fast Refresh enabled for 1 custom loader event - client and server compiled successful ...

Unable to locate module: '@material-ui/pickers' - Material UI React

I encountered an error that said: Material UI React - Module not found: Can't resolve '@material-ui/pickers' in React. Previously, I faced a similar issue with '@date-io/date-fns' but was able to fix it by updating to the latest ...

Utilizing client-side storage within a React project

As part of my React challenge tracking app development, I am looking to implement a feature where users can click on a challenge button, approve it, and then save the chosen challenge name to local storage. Later, this saved challenge will be displayed in ...

Running NPM module via Cordova

After developing an app using cordova, I encountered a challenge where I needed to incorporate a node module that lacked a client-side equivalent due to file write stream requirements. My solution involved utilizing Cordova hooks by implementing an app_run ...

Disappearance of array data

I have been working on creating an array of objects with nested arrays, but I am facing an issue where data seems to go missing in the final step: const args_arr = []; const options_arr = []; let options = ''; let text = ""; for (let i = 0; ...

Is there a way to confirm if the target has been successfully removed from the element using jQuery?

$(".dropdown-toggle").click(function(event) { var target = $(event.target); if (target.is(this)) { $(this).find(".caret").toggleClass("customcaret"); } }); <div class="dropdown-toggle"> <div class="caret"></div> </div> ...

Using JQuery to Enhance the Highlight Effect: Tips and Tricks

Exploring the functionality of the "highlight" JQuery effect: http://docs.jquery.com/UI/Effects/Highlight You have the ability to modify the background color of any DIV element with a fade in/out effect. However, the provided example demonstrates trigge ...

Encountering issues with JSON.Parse in JavaScript leads to errors

I'm encountering issues with JSON parsing in my code and I can't figure out the cause of it. I have a function that calls two ajax functions, one at the start and another in the success function. Everything seems to be working fine until I try to ...

Updating JSON object keys using Groovy

I am working with JSON data received from the server that needs to have its key values cleaned up by shortening their length and removing spaces. While I have successfully manipulated the initial key of an array using put/remove, I am struggling to achieve ...