Beautify JSON data display

My JSON object is displaying differently when I alert it:

https://i.stack.imgur.com/lwNIJ.png

I would like it to show like this instead:

https://i.stack.imgur.com/cVakX.png

function getEmployeeNameById(id){
    return staffArray.find(item => item.id === id).name;
}

var staffArray = [
{"id":"135","name":"Jenny"},
                    {"id":"162","name":"Kelly"}
                 ];
$("#submit").click(function (e) {           
    var mistakes = {};
    
    $(".validation").each(function(){
       var empl_id = $(this).attr('id').replace(/[^\d]/g, '');
       var e_name = getEmployeeNameById(empl_id);
       if(!mistakes[e_name]) mistakes[e_name] = [];
       if ( $(this).val() == "" ) {
           mistakes[e_name].push( $(this).attr('id').replace(/[^a-zA-Z]/g, '') + " must be filled!");
           //errors[w_name].push("second number must be smaller than first");
       }
       if ( $(this).attr('id') == "second-"+empl_id  && ($(this).val() > $('#first-'+empl_id+'').val())) {
        mistakes[e_name].push("second number must be smaller than first");
       }     
    });
    
    alert(JSON.stringify(mistakes, null, 2));
    e.preventDefault();
    e.stopPropagation();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
  First<input id="first-135" class="validation" name="first" type="text" value="5"><br>
  Second<input id="second-135" class="validation" name="second" type="text" value="8"><br>
  Signature<input id="signature-135" class="validation" name="signature" type="text"><br>
<input id="submit" type="submit" value="Submit">
</form>
How do I go about accomplishing this?

Answer №1

Convert your data into a string with this method

const data = {
  "Alice" : [
    "Please enter a valid email address",
    "Password must contain at least one number"
  ]
};

let text = "";
Object.keys(data).forEach(key => {
  text += key + ":\n";
  text += data[key].join(",\n");
});

console.log(text);

Answer №2

Instead of simply using JSON.stringify, try extracting the information from the JSON data stored in the variable errors. Use the format errors["Jenny"] to access a list of errors, and then merge them into a customized string.

Answer №3

It seems like your question may not be related to JSON at all. The JSON displayed is primarily for the alert() function:

alert(JSON.stringify(errors, null, 2));
   // ^^^^^^^^^^^^^^ This creates JSON

If you need to combine array elements, you can utilize both the concatenation operator (+) and the Array.join() method:

alert(w_name + ":\n" + errors[w_name].join(",\n"));

You can adjust the format to meet your preferences.

var w_name = "Jenny";
var errors = {};

errors[w_name] = [];
errors[w_name].push("Second number must be smaller than first");
errors[w_name].push("Signature must be filled!");

alert(w_name + ":\n" + errors[w_name].join(",\n"));

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

Tips for sending an array of inputs to the query selector in Node.js using Cloudant

Currently, I am attempting to retrieve documents from a cloudant database using node.js. While I have successfully managed to obtain results for a single input value, I am encountering difficulty when it comes to querying with an array of inputs. For a si ...

Proper method for verifying line-clamp in a Vue component

I came across a question that aligns perfectly with my current task - determining if text is truncated or not. The query can be found here: How can I check whether line-clamp is enabled?. It seems like my approach may not be accurate, so any guidance on ho ...

Tips for preserving the integrity of square brackets while extracting data from JSON

Everyone: We've decided to utilize Newtonsoft JSON.NET for serializing some C# POCOs, and here's what we have: { "RouteID": "123321213312", "DriverName": "JohnDoe", "Shift": "Night", "ItineraryCoordinates": [ [ 9393, 44 ...

What is the best way to connect a JavaScript file to an HTML file in an Express app?

I have my NodeJS server set up with Express, utilizing Handlebars as the rendering engine. app.use(express.static(publicDirPath)) (...) app.engine("hbs",hbs({ extname: "hbs", defaultView: "main", layoutsDir: path.join(srcDirP ...

Utilizing Scala Play framework for json serialization of parameterized types

Consider the scenario where I have a trait defined like this: trait MyTrait[T] { def myVal: T } And then, I create a case class that extends this trait: case class MyClass(val foo: Int, val myVal: Boolean) extends MyTrait[Boolean] Next, I define an ...

Utilize JSON parsing with AngularJS

My current code processes json-formatted text within the javascript code, but I would like to read it from a json file instead. How can I modify my code to achieve this? Specifically, how can I assign the parsed data to the variable $scope.Items? app.co ...

What are some techniques for transforming text into JSON format?

Beginner inquiry: I'm struggling with manipulating text using JavaScript. Here is the text I want to transform: "5555 55:55: John: New York 6666 66:66: Jack: Los Angeles" My desired output after manipulation: [{ name:"John", address:"New York", n ...

Leveraging the power of the three.js library on the client-side within a vue.js/n

I'm facing a challenge with incorporating the three.js library (installed via npm) to display 3D models on the client side within my nuxt.js application. Despite multiple attempts, I seem to be hitting a roadblock with the import not functioning prope ...

Can a repetitive 'setTimeout' function invocation ultimately cause the JS Engine to crash?

Imagine a scenario where I require data from the server every 10 seconds. A function would be created to fetch the data using AJAX, and then setTimeout would be used to schedule the function to run again: function RetrieveData(){ $.ajax({ url: " ...

What is the best way to notify administrator users when their accounts have exceeded the timeout period?

Working on the website for our high school newspaper, I've encountered a recurring issue on the admin page. Users are getting logged out after creating an article due to a time limit constraint. To address this problem, my goal is to implement an aler ...

Determine the availability of a distant website through AJAX requests

My website runs PHP's cURL to check the online status of 5 different URLs, however, this process tends to slow down the page load time significantly, especially if one of the sites being checked is not working. Someone suggested using jQuery's a ...

Tips on handling multiple text field validation in material-ui for react?

Currently, I am working on developing a form using Material-UI and React.js where I need to validate two TextField components. My goal is to apply the same error and textHelper props to both TextFields. Below is a snippet of my code for reference. Any sugg ...

Issue encountered during rootScope update

I've encountered an issue with my Angular service that updates the $rootScope. The actual updating process works as intended, but it triggers an error in the console that has me concerned. app.service("scroll", function($rootScope, $window) { this ...

Optimal method for parsing JSON data from a mobile client to a web service

Recently, I created a small iphone app that stores data locally. When the user goes online, my goal is to send this data to the server using a JSON stream. However, I am unsure about how to handle the server side using Java. How can I efficiently receiv ...

Obtain a value from a JsonArray and save it in a separate array

Does anyone know how to extract the "score" values from this ArrayofJson dataset? I am looking to store scores 1, 2, 1, 3 in an array like int sample[] = {1, 2, 1, 3}; import org.json.JSONArray; import org.json.JSONObject; p ...

Converting JSON data into a versatile Java object with spatial capabilities

Is there a recommended method or library for deserializing a JSON string into a Java Object containing Geometry (such as JTS) and a list of attributes? I have multiple data sources that I need to query and display on a map with their attribute information ...

Exploring the possibility of utilizing the talks.js library to develop a chat feature within a React application

I'm currently working on integrating the talks.js library to set up a chat feature in my React project. I've followed all the instructions provided at , but unfortunately, it's not functioning as expected. I'm not quite sure what I migh ...

delayed updating of property not visible in angular 10 immediately

I needed to hide a div based on a condition, so I decided to use the hidden property like below: <div [hidden]="isControlDisplayed()?false:true"> The isControlDisplayed() method determines whether to show or hide the div based on the value ...

Tips for utilizing the router instance on a different HTML page within the Backbone JS framework

I'm new to Backbone JS and still learning its intricacies. In main.js, I have created a router class that is included in index.html. I've also created an object of that router class associated with the same HTML page. However, when I redirect t ...

Employing the `instanceof` operator on instances generated by constructors from complex npm dependencies

Context: In one of my npm modules, I've implemented error handling code with a custom error type called CustomError: function CustomError () { /* ... */ } CustomError.prototype = Object.create(Error.prototype); CustomError.prototype.constructor = Cu ...