Breaking down and modifying JavaScript JSON objects

Can someone explain how to separate a JSON object and make updates based on the ID? I've heard about using stringify! But how do I actually implement the function to update the object?

<input type="text" value="{"id":"1","price":"30.00","edit":0},
{"id":"2","price":"8.00","edit":0}" id="json" />

**code:**
var json = $('#json').val().split(',');

for (var i = 0; i < json.length; i++){
  alert(json);
}
//(it looks like it's splitting at every comma it finds).

My goal is to:

  • Split the objects {"id":"1","price":"30.00","edit":0}, {"id":"2","price":"8.00","edit":0}
  • Make updates based on the selected ID.
  • Save and return the same object format with the updated values.

I hope my question is clear enough :)

Answer №1

To avoid string split and parsing, consider using $.parseJSON as shown in the example below:

$.parseJSON("[" + $('#json').val() + "]");

Check out the DEMO here: http://jsfiddle.net/QUTu9/

Furthermore, make sure to fix the quotes in your HTML code like this:

<input type="text" value='{"id":"1","price":"30.00","edit":0},
{"id":"2","price":"8.00","edit":0}' id="json" />

Answer №2

Unfortunately, your code won't function properly due to a quotation issue. The simplest fix is to encapsulate it in single quotes.

<input type="text" value='{"id":"1","price":"30.00","edit":0},{"id":"2","price":"8.00","edit":0}' id="json" />

Avoid splitting it up; instead, utilize JSON.parse

Answer №3

Initially, the syntax appears to be a little jumbled. Make sure to enclose your value in single quotes.

value='{"id":"1","price":"30.00","edit":0}, {"id":"2","price":"8.00","edit":0}'

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

What is the best way to deactivate a button when a certain input field is left blank?

I'm having trouble figuring out how to deactivate a button when specific input fields are empty, while others can remain optional for the process. In my course, we were taught to disable the button until all inputs are valid, so I'm a bit confus ...

What causes Ajax to consistently redirect to a different page following a successful response or error?

I'm new to working with AJAX and I want to utilize it to update data on my page without reloading while also displaying error or success messages. However, when I attempt to submit the form, it redirects me to another page showing validation errors/su ...

Why is the 3rd argument necessary when using useReducer?

According to the information provided in the documentation: [init, the 3d argument] allows you to separate the logic for determining the initial state outside of the reducer. This is particularly useful for resetting the state later in response to an ac ...

Extract information from page 1 to page 2 by utilizing ajax

Greetings, I am currently facing an issue with parsing data using the href get method to retrieve PHP by ajax on another page. Is this achievable? By the way, my framework of choice is CODEIGNITER. This is my HTML href code snippet: <a href="'.b ...

Are you using yeoman with csslint in your project?

As a newcomer to grunt, I am facing challenges in integrating csslint to monitor my project while running "grunt serve" for csslinting. I am specifically struggling with disabling the adjoining classes warning since it is not relevant for IE6 compatibili ...

What is the best way to determine which DOM element triggered a click event?

I currently have a few Card components from material UI, each containing an EDIT button with a corresponding handler. These cards are dynamically added using Map traversal (for this example, I have hard coded two of them). My challenge now is trying to ma ...

What methods are available to modify the colors in an Apex bar chart?

Currently, I am in the process of constructing a bar chart using react, mui, and apex-chart. One specific requirement I have is to modify the colors of the bars displayed on the chart. Despite my efforts in attempting various solutions, I have been unsucce ...

What steps should I take to retrieve JSON data using fetch from my Express server?

After several attempts to use fetch for retrieving JSON data from my express server, I have encountered some issues. While the fetch function works well with JSONPlaceholder, it seems to fail when accessing my express code. Below is the snippet of my fetc ...

Populate HTML dropdown menu with data from an external JSON file

I'm attempting to populate a HTML Dropdown menu with information from an external JSON file, which consists of the following { "Destinations": [ { "destinationName": "London", "destinationID": "lon" }, { "dest ...

Combining and organizing JSON arrays

Having an issue with jq. Received the following data from API: { "items": [4,5,1,3,2], "objectNumbers": [ { "type": "objectNumber", "number": 8 }, { "type": "objectNumber", "number": 7 }, { ...

Master the art of managing filenames with JavaScript

Here is a piece of javascript code that I created: fileName = "Report_" + Name + ".csv" var hiddenElement = document.createElement('a'); hiddenElement.href = 'data:attachment/text,' + encodeURI(data); hiddenElement.targ ...

Beware, search for DomNode!

I attempted to create a select menu using material-ui and React const SelectLevelButton = forwardRef((props, ref) => { const [stateLevel, setStateLevel] = useState({ level: "Easy" }); const [stateMenu, setStateMenu] = useState({ isOpen ...

Can the load() function retrieve an element along with its descendants?

While experimenting with the jQuery load() command, I encountered an interesting scenario. My code looked something like this: $('<div id="box" />').load('my.html div#content', function(){ etc. To my surprise, I was able to retri ...

Utilizing Angular's ng-Grid with Promises

My current setup involves fetching a JSON file through a service to serve as the data source for my grid. The service successfully fetches the data, and the grid renders its basic layout correctly. However, there seems to be an issue with populating the gr ...

What is the best way to retrieve a style property from a <style> tag using JavaScript?

Is there a way to retrieve CSS properties set in the <style> tag in JavaScript, rather than just those set in the element's style attribute? For example: <style> div{background:red;} </style> How can I access these styles, such ...

Rails Unobtrusive JavaScript (UJS) does not seem to be connecting the data-remote

Version of Rails: 3.2.1 Version of Ruby: 1.9.3p125 Browser Used: Chrome 18.0.1025.162 Developers Operating System: Mac OS/X Lion Server's Operating System: CentOS 5 I am attempting to utilize :remote in my link_to call in order to request HTML co ...

Utilizing jq for finding a parent element based on a specific child key/value pair

How can I use jq to select a parent object that contains a child object meeting two filter requirements? For instance, I want to choose all Subnets elements with a child tag having key "Name" and value "TheName". There are two subnets in my example - one ...

Deciphering unique characters within JSON syntax

I am currently using NSJSONSerialization to parse JSON data. NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"url"]]; NSError *jsonError = nil; id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMu ...

The input tag loses focus after its value is updated using a class method in Angular 8.x

Currently, I am working on integrating a credit card payment method and formatting its number through specific methods. Here is how it is done: HTML <div class="form-group" *ngFor="let formField of cardFields; let cardFieldIndex = index;"> ...

Is it possible to refrain from using the object variable name in an ng-repeat loop?

When utilizing an ng-repeat directive to loop through an array, the syntax requires ng-repeat="friend in friends". Inside the template, you can then use the interpolation operator like this {{friend.name}}. Is there a way to directly assign properties to ...