Manipulating JSON data in JavaScript

Currently delving into learning JSON as required for work purposes... I am attempting to dynamically add and delete records to a JSON object... Can anyone shed some light on why I keep receiving an UNDEFINED message? Here is the code... Appreciate any assistance!

<html>
<head>
<title>TEST</title>
<script language="Javascript" type="text/javascript">
 function addC(){
  var index = document.getElementById('type').selectedIndex;
  var type = document.getElementById('type').options[index].value;
  var name = document.getElementById('inpName').value;
  var date = document.getElementById('inpDate').value;
  processJson(type, name, date);
  return false;
 }

 function processJson(type, name, date){
  var count = document.getElementById('counter').value * 1;
  var currentRecords = document.getElementById('holder').value;
  var newRecordType = "{\"name\":\"" + type + "\",";
  var newRecordName = "\"type\":\"" + name + "\",";
  var newRecordDate = "\"date\":\"" + date + "\"}";
  var newRecord = newRecordType + newRecordName + newRecordDate;
  if (count > 0){
   newRecord = "," + newRecord;
  }
  var updatedRecord = currentRecords + newRecord;
  var jsonObj = {"allrows" : "[" + updatedRecord + "]"};
  document.getElementById('counter').value = (document.getElementById('counter').value * 1) + 1;
  document.getElementById('holder').value = updatedRecord;  
 }

 function deleteRow(){
  var toDel = document.getElementById('inpDel').value;
  alert(toDel);
  var current = "[" + document.getElementById('holder').value + "]";
  alert(current);
  var jsonO = {"allRows" : current};
  alert(jsonO);
  var t = jsonO.allRows[toDel].type;
  alert("Deleting - " + t);
  return false;  
 }
</script>
</head>

<body>
<form name="frm" action="">
<table>
 <tr>
  <td>
   <select name="type" id="type">
    <option value="creator">Creator</option>
    <option value="editor">Editor</option>
    <option value="publisher">Publisher</option>
   </select>
  </td>
  <td>
   <input type="text" name="inpName" id="inpName" value="">
  </td>
  <td>
   <input type="text" name="inpDate" id="inpDate" value="">
  </td>
  <td>
   <input type="text" name="inpDel" id="inpDel" value="">
  </td>
  <td>
   <input type="button" name="cmdAdd" value="Add" onClick="return addC();">
   <input type="button" name="cmdAdd" value="Del" onClick="return deleteRow();">
  </td>
 </tr>
 <tr>
  <td><input type="text" name="counter" id="counter" value="0">
 </tr>
 <tr>
  <td colspan="3"> 
   <textarea name="holder" id="holder" rows="20" cols="60"></textarea>

  </td>
 </tr>
</form>
</body>
</html>

Answer №2

You're not working with JSON, but rather JavaScript objects. While JSON stands for "JavaScript Object Notation," it typically refers to serialized objects transmitted over a network.

Let's delve into object literals in JavaScript:

  1. An object is formatted as { key : value, key : value }, where the key doesn't require quotes unless it's a keyword.

  2. An array is structured as [ value, value ].

  3. Arrays are essentially objects in JavaScript.

  4. To access a value within an object, you can use either of the following notations:

    object.key
    object['key']
    

    Using the second notation allows for using a variable as the key.

  5. As arrays are treated as objects, you access array values in the same way:

    array[index]
    

To achieve what you seem to be aiming for, I would approach it like this:

Firstly, a basic function to convert objects into strings:

// CAUTION! : this is a simple toString function. It's advisable to utilize a more robust one
function toString (obj) {
    if (!isNaN(obj))             return ''+obj;
    if (obj === true)            return 'true';
    if (obj === false)           return 'false';
    if (obj === null)            return 'null';
    if (obj === undefined)       return 'undefined';
    if (typeof obj == 'string')  return '"'+obj+'"';
    if (obj instanceof String)   return '"'+obj+'"';
    var ret="";
    if (obj instanceof Array) {
        ret += "[";
        for (var i=0;i<obj.length;i++) {
            ret += toString(obj[i]);
        }
        ret += "]";
    }
    else {
        ret += "{";
        for (var i in obj) {
            if (obj.hasOwnProperty(i)) {
                ret += toString(i);
                ret += ':';
                ret += toString(obj[i]);
            }
        }
        ret += "}";
    }
    return ret;
}

Now, moving on to the remaining code:

var counter_el = document.getElementById('counter');
var count = counter_el.value*1;

// CAUTION! : eval is a quick and dirty JSON deserializer
// it's generally not recommended for use, but works fine in
// this scenario:
eval('var currentRecords = ' + document.getElementById('holder').value);
var newRecord = {
    name : type,
    type : name,
    date : date
}

if(count > 0){
    currentRecords.allrows.push(newRecord);
}
else{
    currentRecords = { allrows : [ newRecord ] };
}

counter_el.value=(counter_el.value*1)+ 1;
document.getElementById('holder').value=toString(currentRecords);

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

PHP is unable to make updates to the record

https://i.sstatic.net/WkUFc.pngI have been working on a function to update the "status" attribute in the "users" table. When the status is set to 1, it indicates that the user is online, while a status of 0 means that the user is offline. While coding a P ...

Discovering the reason behind a DOM element's visual alteration upon hovering: Where to start?

Visit this page, then click on the next button to navigate to the time slots section. As you hover over any time slot, you will notice a change in appearance. Despite inspecting Chrome's developer tools, I was unable to locate a style with a hover dec ...

Enhancing audio control features using HTML and JavaScript

After utilizing various suggestions, I have successfully created a basic audio slider that starts playing sound (at zero volume) when clicked by the user. They can then adjust the volume as needed. My only challenge is that the volume adjustment only occu ...

What are the steps to validate an Ajax form using Dojo JavaScript?

Currently, I am in the process of validating a form that has been written in Javascript/Dojo before sending it via Ajax. Here is the code snippet: <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js" type="text/javascript" djConf ...

Creating an interactive button using RichFaces and Bootstrap for seamless Ajax functionality

I have a challenge with making a fully clickable span or button that includes a Bootstrap refresh glyph-icon. The current code I have inherited only allows the icon itself to be clicked, leaving the area between the icon and button border unclickable. This ...

Utilizing jQuery and AJAX, execute a PHP query based on the user's input and showcase the query's outcome without reloading the page

For the past 24 hours, I've been on a quest to find a solution. Although I've come across similar inquiries, either the responses are too complex for my specific scenario (resulting in confusion) or they are of poor quality. The crux of my issue ...

In Cypress, I am trying to specifically choose only numerical values from a dropdown menu. However, the list contains a mix of alphanumeric and numeric values

Looking to streamline: This is my code: cy.get('[role=presentation]') cy.get('[role=row]').find('td') .get('[role=gridcell]').eq(9).click().wait(2000) cy.get('[role=listbox]').get('[role=option]& ...

Using jQuery, you can disable an option upon selection and also change its border color

learn HTML code <select name="register-month" id="register-month"> <option value="00">Month</option> <option value="01">January</option> <option value="02">February</option> <option value="03"& ...

How can I designate the file name when using Ajax to export in Excel formatting?

Can you help me with the code to set a specific filename for downloading an Excel file? if(comp_id != "Select Company") { $.ajax({ url: 'includes/export.php', data: { action: 'compreport', 'comp':comp_i ...

Guidelines for utilizing recursion in order to calculate the sum of specified values within a multidimensional array

I am dealing with a complex object data that resembles the structure provided below. My objective is to calculate the total direct package values for the top users, or "parents" compute the combined nested indirect package values from the subtree of "ch ...

I am sometimes experiencing issues with activating ajax code using Bootstrap 3 modal

I'm stumped trying to find a solution for this issue. Currently, I am utilizing the bootstrap modal to retrieve ajax content from a specified URL. To prevent content overlap, I am using $.removeData() when reloading the content. The problem arises w ...

When a cookie is set in NextJS with a static export, it reverts back to its original

My current project involves building a multilingual website. To handle language selection, I have implemented a system where the chosen language is stored in a cookie and retrieved using getInitialProps in the _app file, which is then passed as a context A ...

Is it possible for me to display dynamic content and utilize a template engine like (ejs)?

Currently, I am in the process of developing a weather application to enhance my skills with express and ejs. At the moment, I'm utilizing app.get to fetch data from darkSky's API successfully, and I can display it on my index.ejs page. My next ...

Ways to exclusively trigger the onclick function of the primary button when dealing with nested buttons in React.js

Let me elaborate on this issue. I have a List component from material-UI, with ListItem set to button=true which makes the entire item act as a button. Within the ListItem, I have added a FontAwesomeIcon. To hide the button, I set its style to visibility: ...

What is the best way to navigate back on a button click in jquery AJAX without causing a page refresh?

Is there a way to navigate back without refreshing the page? I am fetching data dynamically using AJAX, but when I try to go back using the browser button, it takes me all the way back to the starting point. Let's look at the situation: 3 Different ...

Ways to reuse test cases across different test suites in Protractor

There are some shared test cases that can be utilized across different test suites. For example, suppose suite x and suite y both require the same set of test cases to function properly. To address this, a separate .js file containing the shared code has ...

Errors that occur during Javascript runtime in the Express framework

I'm currently working on an Express app with several routes. One of them looks like this: router.post('/upload', (req, res) => { let audioFile = req.files.audioFile; const file = __dirname + '/../' + req.body.uploadLocation ...

What is the proper method for encoding HTML within JAVASCRIPT and JSON, and then decoding it in PYTHON?

Within my JAVASCRIPT array named allPois, there are multiple pois objects structured like this: var poi = { title: pois[x].title, lat: pois[x].position.lat(), lng: pois[x].position.lng(), html: pois[x].html ...

Guide on retrieving the mouse button press from a command event using XUL

There appears to be a difference between the XUL command and click events. While my function is called when using the command event, the event object does not include the button property. I'm trying to figure out: how can I determine which mouse but ...

Amazon Lex: Transforming Speech to Text with Audio Technology

Is there a JavaScript SDK provided by Amazon for converting audio files to text using Amazon Lex? I am currently working on a Node.js application and would like to achieve this functionality. ...