Counting objects in a JSON string and splitting it in JavaScript without prior knowledge of the total number

My JSON structure contains multiple values like the following:

[{"Id":22,"Title":"München - Stockholm 31.01.2017 15:00"},{"Id":23,"Title":"Stockholm - München 01.02.2017 18:00"}]

I have successfully split one of them using this code:

var text = "[{\"Id\":22,\"Title\":\"München - Stockholm 31.01.2017 15:00\"}]";
console.log(JSON.parse(text)[0].Title.split(","));

How can I split all elements within the JSON structure?

The approach below works for 2 items, but I want a dynamic solution.

var text = "[{\"Id\":22,\"Title\":\"München - Stockholm 31.01.2017 15:00\"},{\"Id\":23,\"Title\":\"Stockholm - München 01.02.2017 18:00\"}]";

var count = Object.keys(text).length;
console.log(count);

for (var i=0; i < 2; i++){
    console.log(JSON.parse(text)[i].Title.split(","));
}

I tried to use the count variable in the loop, but it gave unexpected results. Any ideas on how to achieve this?

Thank you for your help!

Answer №1

To begin with, it's important to utilize the JSON.parse function:

var data = "[{\"Name\":\"John\",\"Age\":30},{\"Name\":\"Alice\",\"Age\":25}]"
var parsedData = JSON.parse(data)
var length = parsedData.length

console.log(length)

Remember that when dealing with arrays and objects, you need to work with actual arrays and objects. A string may appear like an array, but it consists of individual characters.

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

Communicating between ASP.NET and an Excel workbook: A comprehensive guide

Is it possible to integrate an Excel document into a webpage and interact with the Excel control through backend coding, whether in JavaScript or Asp.NET? ...

Comparing global variables in ng-switch: Best practices

I'm currently utilizing the AngularJS $rootScope object to expose some global constants that should be accessible to both controllers and views: var app = angular.module('myApp', []); app.run(function ($rootScope) { $rootScope.myConsta ...

How to display JSON data in an Android ListView

When parsing my URL, I receive the following JsonObject: {"status":0,"items":"1333333454510|-7611868|-7222457" Now I need to extract each number separately as a long. If I attempt to convert it to a string, I encounter an error: org.json.JSONException: V ...

Can PHP be incorporated with vBulletin seamlessly?

I am looking to seamlessly integrate vBulletin into a PHP page. I don't want to create a skin that simply matches the site's appearance, but rather have the forum fully integrated with the site. Of course, the skin would need to be modified to ma ...

I'm having trouble locating the container with only one child element in JavaScript

I am currently working on a project where I need to locate a specific container using JavaScript. More specifically, I am looking to target the container that houses the required address. My aim is to assign a class to the container of the requested addre ...

The IP validation feature in the textbox is not performing as anticipated

My goal is to have a textbox that receives an IP address and validates it before submission. To achieve this, I've developed a JavaScript class called `validityCheck`. In my main Vue.js component, I aim to utilize this class to validate the input&apo ...

Using a .NET Web-API controller variable as a parameter in a JavaScript function

I am looking to send a "variable" from the controller to a JavaScript function. The code I have implemented is as below: <div ng-controller="faqController"> <div ng-repeat="c in categories"> <h2 onclick="toggle_visibility(&apos ...

How can we properly format a string to be included in a JSON string using Kotlin?

There is a challenge of receiving certain string that becomes invalid when converted to JSON, requiring it to be escaped. Is there a pre-existing function in Kotlin for escaping strings? ...

Is it possible to transform this nested promise into a chain instead?

This situation is just a scenario | then (items) | then (items, actions) getItems() | getActions(for:items) | apply(actions -> items) :promise | :promise | model <= items | | :sync ...

Ways to extract a parameter from a React component

Currently, I am working with React and using an API call (ReviewerService.getReviewers()) that returns an array of values: 0: {id: 1, firstName: 'John', lastName: 'Doe', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_ ...

When making an HTTP GET request followed by another GET request in Express, it results in an error with undefined parameters on the

When I open a form that has a link to a list and try to access the list, I encounter an "id" undefined error for the form we came from, which was already functional. The issue arises when I have a GET page where I present a form to modify a record at /loc ...

Executing a custom module that is installed globally on a Node server

After creating a custom module called "nawk" using npm, I am facing an issue while trying to run it as a command on my computer. Included in the package.json file: { "name": "nawk", "preferGlobal": true, "version": "0.0.1", "author": "My Name < ...

Mastering sorting in AngularJS: ascending or descending, the choice is yours!

I have set up a table view with infinite scroll functionality. The table contains 2000 objects, but only shows 25 at a time. As the user scrolls to the bottom, it loads an additional 25 elements and so on. There is a "V" or "^" button in the header that sh ...

Aframe audio gap control

I am currently working on a scene that includes a looping sound: <a-assets> <audio id="ambience" src="./audio/ambient.mp3" preload="auto"></audio> <a-entity id="ambience_sfx" sound="src: #am ...

Gradient in Half Circle With JavaScript

How can I achieve a gradient effect within a circle using the following initial code: HTML: <div class="progresss"> <div class="barOverflow"> <div class="bar"></div> </div> <span>10</span>% </d ...

Render and download the file concurrently while displaying the view in Express

I'm looking to accomplish a task in Express where I can render a file and download it simultaneously. My current code looks like this: res.attachment('filename.csv'); res.render('pages/result', { data }); However, with this setu ...

Removing information from the app.component.html file in Angular 6 and reflecting those updates in the view

I currently have a service that retrieves a list of data and displays it within the app.component.html. Below is the code snippet used to display the data: <ul> <li *ngFor="let data of retrieveData"> {{ data.id }} - {{data.title} ...

I am not getting any reply in Postman - I have sent a patch request but there is no response showing up in the Postman console

const updateProductInfo = async (req, res) => { const productId = req.params.productId; try { const updatedProduct = await Product.findOneAndUpdate({ _id: productId }, { $set: req.body }); console.log("Product updat ...

Having trouble with Node.js POST request; no specific error message displayed

Currently facing a challenge in communicating with an API using nodejs. I've exhausted all possible solutions, including utilizing different request modules and altering the format among other attempts. Here is the code snippet... var request = requ ...

When trying to decode the JSON object from the request body using `json.loads()`, Django throws an error stating "Unable to decode JSON object"

I am currently developing an application using Django along with Django Rest Framework and AngularJS with CoffeScript. I have been following a tutorial at as my guide. The issue I am facing revolves around passing JSON data from the client side. Even when ...