Remove hash symbol from JSON object using Javascript

After converting a JSON string into a Javascript object, I encountered an issue with accessing a specific value within it. Here is an example of what I'm dealing with:

"link": {
            "#tail": "\n\n\t\t",
            "#text": "http://static2.server.com/file.mp3"
          },

I am trying to retrieve the value of "text" in Javascript, but the "#" symbol is causing difficulties.

To address this problem, I attempted to clean up the string using the following code snippet:

var myJSONString = JSON.stringify(response);
      var myEscapedJSONString = myJSONString.replace(/[^\u0000-\u007F]+/g, "").replace("#","t");

Unfortunately, this approach did not successfully remove the "#" symbol from the key part even after converting the object into a string using stringify.

Answer №1

There doesn't seem to be an issue with using the # as a key in this context. Any valid string can serve as an object key. However, if you prefer to avoid using strings, you can replace it using regular expressions (assuming the hash character is only at the beginning of each key):

const cleanObj = JSON.parse(JSON.stringify(response).replace(/\"#/gm,'"'))
console.log(cleanObj.link.text);

I didn't encounter any problems when accessing and cleaning up through JavaScript either.

var cleanObject = { link: {} };

Object.keys(response.link).map(function(key) { 
    cleanObject.link[key.substring(1)] = response.link[key];
})

Check out the Fiddle here: https://jsfiddle.net/p5cvvqzu/

Answer №2

Have you considered removing the # symbols from the keys before utilizing the object?

function removeHashes(obj) {
    var updatedObj = {};
    Object.keys(obj).forEach(function(key) {
        updatedObj[key.substr(1)] = item[key];
    });
    return updatedObj;
}

By implementing this function, you will receive a new object with the hashes removed from the original object's keys.

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

Executing a Javascript function post AJAX page loading

I'm not a coding expert, so I hope my question is still clear. Essentially, I have an index.php page with filters (by project, year, month) that send variables to filterData.php after clicking submit. These variables are then used in SQL statements t ...

Guide on creating a conditional column in a kendo UI grid with the use of AngularJS

Is there a way to dynamically add a column to the Kendo UI grid based on JSON data? Consider the following JSON input: [{ "ProductID": 1, "ProductName": "Chai", "Supplier": { "SupplierID": 1, "SupplierName": "Exotic Liquid ...

Establishing a self-referential relationship in Sequelize using a junction table

I am working on creating a sequelize relationship that represents the concept of: An item being composed of a specific quantity of other items. Database tables Item (itemId, name) Ingredient (ingredientId, itemParentId, itemChildrenId, amount) Sequelize ...

Transforming Thomas J Bradley's signature pad JSON into a PNG file using C# programming language

I have been experimenting with the Signature Pad plugin developed by Thomas J Bradley and successfully converted JSON signature to PNG using PHP. Now I am looking to achieve the same result using C#. There is a supplemental class called SignatureToImageDo ...

The initial render of children elements in React Google Maps Api may not display properly

I am struggling to incorporate the Google Maps API into my app. Everything works smoothly until I try to display a Marker at the initial rendering of the map. The Marker does not show up, but if I add another Marker after the rendering is complete, then it ...

Steps for filling in checkboxes within a table using data from a Django model

In the html table of my application, there is a column that includes a checkbox, which allows users to check or uncheck it. The status (boolean) of this checkbox is stored in the Subscriber model under Subscriber.participates. All instances of Subscriber a ...

The error of 'illegal invocation' occurs when attempting to use input setCustomValidity with TypeScript

I am new to the Typescript world and currently converting one of my first React applications. I am facing an issue while trying to set custom messages on input validation using event.target.setCustomValidity. I keep getting an 'Illegal invocation&apo ...

Issue with Angular binding not updating after being assigned in promise.then() function

Within my angular application, I have a $scope variable labeled as user which contains a name property. Whenever I click on a link to set this user variable to "test": <a href="#" ng-click="setUser()">Set User</a> Using the following functio ...

Fade out the jQuery message after a brief 2-second pause

In my Rails application, I encountered an issue with a flash message that appears after successfully completing an AJAX action. The message displays "Patient Added" but does not include a way to close it without refreshing the page. To address this, I atte ...

The functionality of this code is effective, however, it would be more efficient if it were implemented as a loop

While this code works, it has limitations. I believe adding some iteration would improve its functionality, but I am unsure of the best approach to take. For instance, how can I efficiently check 20 items instead of just 4, and have the flexibility to eas ...

Updating JSON data from PHP using jQuery periodically

I currently have a PHP script that is running multiple queries, saving the results in a multidimensional associative array, and then encoding it as JSON. The structure of my JSON file looks like this: {"1":{"name":"Bob","score":18},"3":{"name":"Robert","s ...

Using the JavascriptExecutor in Selenium WebDriver

Having trouble executing the function doFilterOffer() on this page. An error stating missing ; before statement keeps popping up. Can you pinpoint the issue in the syntax provided below? if (driver instanceof JavascriptExecutor) { ((Javascr ...

Cookies cannot be used in browsers other than Chrome, nor can HTML5 local storage

Currently, I am developing a javascript tool that is designed to save a user's selections locally and then reload them when the page is revisited. While this feature works perfectly in Chrome, it seems to be non-functional in IE8 and Safari. I have e ...

Stopping the execution in JavaScript: Is there a way to do it?

Here is a link with embedded JavaScript code: <a style="padding: 5px;" onclick="confirmMessage(); $('contact_693_').show(); $('errors_693_').hide(); this.hide(); $('dont_693_').show();; return false;" id="the_link_693_" hr ...

Using HTML5 Canvas: Implementing an Image.onload() function through Image.prototype

I am trying to create a simple function that will refresh the canvas automatically when an image is loaded. The idea is to be able to use code like this: var map = new Image(); map.onloadDraw(); map.src = "images/" + worldmapCanvasShapeImage; Currently, ...

Adding pointlights to the camera in three.js is a great way to

I have written some code to add two lights on the camera that move along with the orbitcontrols. However, the lights and spheres are not visible for some reason. Can someone help me identify the issue in my code? var sphere1 = new THREE.Mesh( new THREE.Sp ...

Updating global variable in JavaScript at inappropriate times

Within this code: window.g_b_editEnable = false; window.g_a_PreEditData = 'hello'; function EditRow(EditButton){ if(!window.g_b_editEnable){ window.g_b_editEnable = true; var a_i_Pos = a_o_table.fnGetPo ...

Performing a JQuery Event only once

Trying to initiate a JQuery Ajax event for multiple buttons. The following code is found in index.php file : <?php foreach($data as $d) { $myid = $d['id']; $mystatus = $d['status']; ?> <div class="input-group- ...

What is the optimal method for interacting with a backend service in AngularJS?

As a newcomer to AngularJS, I am seeking advice on the best approach to tackle my current issue. The challenge at hand involves dealing with a service that returns a rather intricate JSON object like the one shown below (but even more intricate!): var com ...

What is the best way to implement a conditional data-attribute tag in order to trigger JavaScript functionality?

Is there any way to conditionally apply JavaScript or jQuery code in an HTML Template? For example, if a data-id attribute with the value "no-copy" is found inside the body tag, certain JavaScript code will be applied. To explain it more simply, I have J ...