Guide to modifying the value of a JSON attribute in JavaScript

Here's a snippet from my json file:

{
 "@id": "2",
 "@samsid": "d7058536c89b46c0b58117eff64372f7",
 "@productname": "Another paid for",
 "@downloaddate": "2013-05-28 11:37:12Z",
 "@downloadlocation":
    "2AFoGZVJpFHzspQD9UoE2C4VFYc8idiO4ebaRx4uEvtG+79DjkOUjJQjp9lJdSk54KIbFqzr",
 "@upgradeavailable": "2wECEpVJpFHS",
 "@downlaodstatus": "3QGf15VJpFFrUzr6oxwoew=="
}

I am looking to change the value of the attribute @id, for example changing @id:2 to @id:4.

What would be the best approach to achieve this?

Answer №1

Important Update: Since you indicated that you want to store this data in a file, here's a suggestion: you can assign the JSON object to a variable and then use JSON.stringify() to convert it into a string before writing it to your backend file. This approach will vary based on your system architecture and design.


It seems that having special characters like @ in the keys of your JSON object requires retrieving and setting them differently, as shown below:

// Example of assigning values with special characters
var data = {
"@id": "2",
"@samsid": "d7058536c89b46c0b58117eff64372f7",
"@productname": "Another paid for",
"@downloaddate": "2013-05-28 11:37:12Z",
"@downloadlocation":
   "2AFoGZVJpFHzspQD9UoE2C4VFYc8idiO4ebaRx4uEvtG+79DjkOUjJQjp9lJdSk54KIbFqzr",
"@upgradeavailable": "2wECEpVJpFHS",
"@downlaodstatus": "3QGf15VJpFFrUzr6oxwoew=="
};
alert(data["@id"]); // outputs 2
data["@id"] = 4;
alert(data["@id"]); // now shows 4

Check out this live demo: https://example.com/js-demo

Answer №2

When working with JavaScript and utilizing various libraries, consider implementing a similar approach like the following code snippet (specifically using popular jQuery).

let data = JSON.parse('{"@id": "2","@samsid": "d7058536c89b46c0b58117eff64372f7","@productname": "Another paid for","@downloaddate": "2013-05-28 11:37:12Z","@downloadlocation": "2AFoGZVJpFHzspQD9UoE2C4VFYc8idiO4ebaRx4uEvtG+79DjkOUjJQjp9lJdSk54KIbFqzr","@upgradeavailable": "2wECEpVJpFHS","@downlaodstatus": "3QGf15VJpFFrUzr6oxwoew=="}');
data['@id'] = 4;
let newData = JSON.stringify(data);

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 reason for the lack of uniqueness in Mongo ObjectIDs?

As per the documentation available from MongoDB, ObjectID's are supposed to be generated using a specific format: An ObjectID is a 96-bit number consisting of: a 4-byte timestamp representing seconds since the Unix epoch (up until the year 2106) a ...

What are the steps to incorporate SVG into a React Native project?

I'm in the process of integrating bootstrap icons into my react native project, but I've been having trouble finding clear instructions on how to render an SVG in react-native. Can anyone provide some guidance on this? ...

When a node using express encounters :id, it is directed to a specific location

Currently, I am in the process of creating a small API collection to familiarize myself with nodejs using express. In my project, I have included the line app.use("/v1/phrases", phraseRouter); Within the router file, the code looks like this: co ...

onPropertyChange function exclusive to Internet Explorer

In Internet Explorer, the onPropertyChange event is functioning properly. I have utilized onPropertyChange to input text into one textbox and simultaneously display the same text in another textbox. Are there any alternate methods available to address this ...

Updating input value in React on change event

This is the code for my SearchForm.js, where the function handleKeywordsChange is responsible for managing changes in the input field for keywords. import React from 'react'; import ReactDOM from 'react-dom'; class SearchForm extends ...

Dealing with throwing Exceptions in jest: A guide for developers

I have developed a method that throws an exception when the provided password does not match a regex pattern. I attempted to handle this in Jest. it('Should prevent insertion of a new user if the password doesn't match the regex', async () ...

React's setState() not reflecting state changes when clicked

I have developed a component that displays data from a Redux store grouped by week. To ensure the week's relevance is maintained within this component, I decided to store its value in local state as shown below: constructor(props) { super(props ...

Enhancing Website Visibility: Utilizing PHP and JQuery to Update Page Content for Viewers

Imagine having a social networking platform where users can post updates and see them appear in real-time on their timeline. The challenge arises when these updates are only visible to the user currently logged in on a specific device. How can we utilize j ...

Comparing two arrays in Javascript to find identical values

I am faced with a challenge involving three arrays. One array contains static values, another array contains dynamic values, and the third array is intended to store values that are present in both of the other arrays. My goal is to iterate through the ar ...

bootstrap 4 - logo in navbar brand stays the same even when scrolling

I integrated Bootstrap 4 and successfully created a navbar. However, I am encountering a conflict when trying to change the navbar logo upon scrolling down. Despite my efforts, it is not functioning as expected. Does anyone know how to resolve this issue? ...

Ways to access text content in an HtmlTableCellElement

I am currently working on a jQuery tic-tac-toe project and facing an issue with iterating through the board to save the values of each cell in an array. I have tried using .text() and .value(), but both returned undefined index.html: <html> < ...

There is no Api.js file in the Cordova iOS platform

I have been attempting to integrate the iOS platform into a new Cordova 7.0.1 project, but I continuously encounter the error mentioned in the title of this post. Despite following the steps outlined in this thread here, including removing and re-adding ...

Delete any classes that start with a specific prefix

Within my code, there is a div that holds an id="a". Attached to this div are multiple classes from different groups, each with a unique prefix. I am uncertain about which specific class from the group is applied to the div in JavaScript. My goal is to r ...

The damping effect in three.js OrbitControls only activates when the mouse is pressed, however there is no damping effect once the

I find it difficult to articulate: Currently, I am utilizing OrbitControls in three.js and have activated damping for a smoother rotation with the mouse. It is somewhat effective but not entirely seamless. When I click and drag, the damping feature works ...

Grails is experiencing a surge of duplicate events being triggered simultaneously

In my _test.gsp layout, I have a 'click event' that is triggered when the layout is rendered as shown below. <div id="testid"> <g:render template="test"/> </div> When I click on the event in the _test.gsp layout, it trigge ...

cdkDropList does not function properly when used with ng-template in a dynamic component list

Exploring the new Drag&Drop features introduced in Angular Material 7, I am dynamically generating components using ng-template. <div cdkDropList (cdkDropListDropped)="dropLocal($event)"> <ng-template #components></ng-templat ...

Values do not appear as expected post PDF conversion using wkhtmltopdf

Currently, I am updating certain values within my HTML page by following this process: The function: function modifyContent(){ var newTitle = document.getElementById('myTextField1').value; if( newTitle.length==0 ){ alert('Plea ...

Utilizing AJAX in jQuery Mobile for Collapsible Content

I am currently generating a variable number of these elements using a foreach() loop: <div id="<?php echo $data['id']; ?>" data-role="collapsible" data-theme="a"> <h1 style="white-space: normal"><?php echo $data['te ...

Automatically close the popup each time it is displayed (using jQuery/JavaScript)

I am having issues with auto-closing my popup each time I open it. The current code I have only closes the popup the first time, requiring me to refresh the browser in order to auto-close it again. Can someone please assist me in writing a new code that ...

Import objects into THREE.js using OBJLoader, convert to Geometry, apply transformations, and finally convert to BufferGeometry

Trying to figure out why the geometry loaded with OBJLoader cannot be smoothly shaded. var loader = new THREE.OBJLoader(manager); loader.load('/manmodel/js/man.obj', function (object, materials) { console.log(object); console.log(materia ...