The JSON data rendered by Angular is causing disturbance

I am trying to create JSON from a multi-array in the following format:

var qus ={ 
{ 
"qus" :"what is your name?",
"option1" : {"ans" : Alex, "cor:"false"},
"option2" : {"ans" : Hervy, "cor:"false"},
"option3" : {"ans" : Rico, "cor:"true"},
"option4" : {"ans" : Tom, "cor:"false"},
},

{ 
"qus" :"what is your brother's name?",
"option1" : {"ans" : Alex, "cor:"false"},
"option2" : {"ans" : Hervy, "cor:"true"},
"option3" : {"ans" : Rico, "cor:"false"},
"option4" : {"ans" : Tom, "cor:"false"},
},

}

However, when I input the array values through a textarea, it fails to generate the JSON correctly. You can see the issue with the generated code here: http://plnkr.co/edit/hvuLXL1SPntlqtAV8iEW?p=preview. It seems to be adding unnecessary line breaks.

In another example, everything gets distorted and broken up like this: http://plnkr.co/edit/5qzsSSzv6oXV4QRpPa36?p=preview.

Could you help me understand why extracting values from a textarea is causing these issues? How can I fix the messed-up Plunkers to get the desired JSON output?

Answer №1

To properly iterate through the "objects" object, which is currently in string format, you must first use JSON.parse to convert it into an array. Using a for-in loop on the string will only iterate through each character instead of each element. Once you parse the JSON string, you can access the array and continue with your logic.

Consider using the following code for your scope.generate function:

http://plnkr.co/edit/YW3jFTrTgdH4FfitfeMJ?p=preview

$scope.generate = function() {

  var objects = document.getElementById("inpt").value;

  var el = document.getElementById("out");

  var newObj = JSON.parse(objects);
  el.innerHTML += 'var qus ={ <br>';

  for (i in newObj) {
    var qset = newObj[i];

    el.innerHTML += '{ <br>';
    el.innerHTML += '"qus" :"' + qset[0] + '",<br>';

    for (n in qset) {
      if (n == 0) continue;
      var nameset = qset[n];

      el.innerHTML += '"option' + n;
      el.innerHTML += '" : {"ans" : ' + nameset[0];
      el.innerHTML += ', "cor:"' + nameset[1] + '"},<br>';
    }

    el.innerHTML += '},<br><br>';
  }
  el.innerHTML += '}';
  //el.innerHTML = JSON.stringify(objects);
  console.log(objects);

};

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

Do individual JavaScript script tags operate independently of one another in terms of error handling?

My main goal is to establish a connection to my server using websockets and send messages to the browser for remote page reloads. I want to ensure that this code runs independently of any other errors on the page, allowing me to remotely refresh the page i ...

What is the best way to retain previous values without using an object array to store values in a React state?

My approach involves storing the previous values in an array of objects, where each object represents a key-value pair. For example: [{ActFollow: 'BlN'},{ActSendGift: 'BlY'},{ActSubscribe: 'BlY'}]. However, I aim to transform ...

JavaScript onClick event not functioning properly on iOS devices

I have created a code that can detect when a user clicks on a cell in a table and retrieves the background color set for that cell. Everything works perfectly on my desktop computer, but when I attempt to use my iPad, it does not respond. I attempted to u ...

Finding the index of an element within an array using Google BigQuery

Is there a way to find the position of an element in an array within Google BigQuery? Similar to using the array_position function in Postgresql? Specifically, I am looking to determine the array position of an element after unnesting the array: WITH dat ...

Learn the process of transmitting information to Thingsboard using HTTP protocol

Currently, I have thingsboard installed on my Windows local machine, and I am looking to send data from a CSV file using an HTTP POST request. In order to achieve this, I am required to develop a JAVA program that can facilitate the sending of data from ...

The data from my ajax code is not being successfully transmitted to the database

I'm having trouble using ajax to add data to the database. I'm not sure if the issue lies in the ajax code or the PHP code. Here is a snippet of my code: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></ ...

Finding and comparing a specific portion of a text in JavaScript: A guide

Can you help me with a JavaScript algorithm that can find a substring within a string? subStringFinder('abbcdabbbbbck', 'ab') This should return index 0. Similarly, subStringFinder('abbcdabbbbbck', 'bck') should ...

The SmoothShading feature of THREE does not alter the geometry

I am having trouble with smooth shading on my model - the polygons are still clearly visible and switching between smooth and flat shading in the three.js inspector isn't making a difference. The OBJ file contains vertex normal data, so I don't t ...

JQuery - Select element by clicking outside

I'm trying to figure out how to hide an element when clicking outside of it. Found a solution at: https://css-tricks.com/dangers-stopping-event-propagation/ $(document).on('click', function(event) { if (!$(event.target).closest('#m ...

Maximizing the worth of itemtype using jQuery: A guide

My goal is to include an 'itemtype' attribute in the body tag, body.page-body.ng-scope.device-lg(itemscope='', itemtype='') I attempted the following method $('body').add(itemtype='t1'); Unfortunately, ...

An easy way to add an array to another array within a Redux reducer

Imagine having this condition in the reducer: case POST_LOAD_SUCCESS: return { ...state, posts: [...payload] } The payload for this action is an array [{post_1},{post_2},{post_3},{post4},{post5}]. When this acti ...

Foundation of Worldwide ngResource

In my angular service, I have multiple factories spread across different js files. They all require a common base for queries: 1) Authorization: Bearer token (header) (mandatory after login) 2) AccessDateTime, UserIPAddress (mandatory before login) 3) ...

Defining variables within a jQuery function

Within my initialization function (init), I have defined some variables and an animation that utilizes those variables. The challenge arises when I want to use the same animation/variables in my clickSlide function. http://jsfiddle.net/lollero/4WfZa/ (Un ...

Techniques for eliminating single quotes from string arrays and then creating a new array by separating them with commas

I have an array of elements containing IP addresses with single quotes. I need to remove the single quotes and separate each IP address into new values, storing them as strings in another array using JavaScript. let myArray = [ '10.202.10.800,10.202 ...

The ion-content scrolling directive is failing to show any displayed information

Within my Ionic application, I have a very simple HTML structure: <ion-pane> <ion-header-bar class="bar-stable"> <h1 class="title">Ionic Blank Starter</h1> </ion-header-bar> <ion-content> ...

What could be the reason for the malfunction of my error handler in ExpressJS?

Currently, I am in the process of constructing an API using ExpressJS for one of my projects and am keen on incorporating error handling. Despite consulting various online resources for guidance, I have experimented with different approaches to implement e ...

Tips for creating PHP code that can take a JSON string as input and then insert it into a SQL server

Currently, I am attempting to generate a Json String from my phone and then upload it to my SQL server. However, I am encountering difficulties in figuring out how to output the Json and write the PHP code for this process. Despite trying numerous methods, ...

Unraveling URLs in JSON with TypeScript

After retrieving a Json string from the BE API, I am parsing it into an array of Products[]. This collection is structured as follows: class Products { ProductId: number; ProductName: string; Price: number; ProductUrl: string; } The issue I' ...

What is the best method for concealing a specific element on the screen using ReactJS?

I'm looking for a way to have text displayed on the screen that is only hidden when a button is pressed, but I'm struggling to figure it out. I had the idea of using useState in this way: const [textVisibility, setTextVisibility] = useState(true) ...

Issues encountered when trying to use the export default syntax in Vue components

Programming Issue I attempted to execute the provided code, but unfortunately, it does not work and no output is visible in the browser. Is there an alternative method for writing code within <scripts setup> </script>? I have understood that f ...