Creating a hash from a string in Javascript

I'm struggling with the process of converting a string into a nested hash in JavaScript.

Here is the string I want to convert:

"{'btc_usd': {'price': 376.2, 'volume': 42812.69, 'change': -0.5},'btc_cny': {'price': 2519.39, 'volume': 67148.51, 'change': -85.13},'ltc_usd': {'price': 3.068, 'volume': 4735.55, 'change': -0.58},'btc_ltc': {'price': 0.00805433, 'volume': 153.33, 'change': -0.76},'btc_eth': {'price': 0.00660196, 'volume': 6428.98, 'change': 5.87}}"

I aim to enable hash['btc_usd']['price'] to return 376.2.

How can this be achieved?

Despite trying the following code, it doesn't execute as expected:

var string="{'btc_usd': {'price': 376.2, 'volume': 42812.69, 'change': -0.5},'btc_cny': {'price': 2519.39, 'volume': 67148.51, 'change': -85.13},'ltc_usd': {'price': 3.068, 'volume': 4735.55, 'change': -0.58},'btc_ltc': {'price': 0.00805433, 'volume': 153.33, 'change': -0.76},'btc_eth': {'price': 0.00660196, 'volume': 6428.98, 'change': 5.87}}"
var results=JSON.parse(string);

Answer №1

Have you considered utilizing the JSON format directly?

let data = "{'btc_usd': {'price': 376.2, 'volume': 42812.69, 'change': -0.5},'btc_cny': {'price': 2519.39, 'volume': 67148.51, 'change': -85.13},'ltc_usd': {'price': 3.068, 'volume': 4735.55, 'change': -0.58},'btc_ltc': {'price': 0.00805433, 'volume': 153.33, 'change': -0.76},'btc_eth': {'price': 0.00660196, 'volume': 6428.98, 'change': 5.87}}";
data = "obj = " + data + ";";
eval(data);

console.log(obj.btc_usd.price);

This method is straightforward, but it does have its drawbacks: using eval() can pose security risks if the source of your string is unknown. Additionally, it may be resource-intensive, especially when processing a large number of entries in a loop.

Answer №2

The key difference between the provided string and valid JSON is the use of single quotes instead of double quotes. To rectify this, simply replace all occurrences of single quotes with double quotes and then proceed to parse the modified JSON.

str = str.replace(/'/g, "\"");
var result = JSON.parse(str);

It's important to note that this solution assumes there are no string literals containing single quotes within the JSON structure (e.g. {'name': 'John O\'hara'}).

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

Updating the key within an array of objects

In my array of objects, I have the following data: arrayOfObject = [{'key1': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}] I know the name of the key that I want to replace in my array : var keyString = 'key1&apos ...

Tips for Maintaining the Execution of a JavaScript Function Within a Class until the Browser Window is Closed (Web Development)

The title might be a little confusing, so let me clarify here: I have implemented a popup that appears in the bottom right corner of a specific page on my website. The popup is working as intended (it shows up when the page is initially opened and can be ...

Using jQuery to fetch data asynchronously

I am currently dealing with a web application that needs to carry out the following task. It must send GET requests to a web service for each date within a selected date range, yet this process can be time-consuming. Since I plan to visualize the retrieved ...

Utilizing Javascript to load and parse data retrieved from an HTTP request

Within my application, a server with a rest interface is utilized to manage all database entries. Upon user login, the objective is to load and map all user data from database models to usable models. A key distinction between the two is that database mode ...

The call stack size has been exceeded in Next.js, resulting in a RangeError

Currently attempting to deploy my project on vercel.com but encountering an error specifically with 3 pages that have no internal errors. An error occurred while prerendering the page "/applications". For more information, visit: https://nextjs.org/docs/me ...

"Could you please provide me with further details on how to use sequelize

I recently started working with node js and I used sequelize-auto to generate the models. However, I encountered an error when following the guidance provided in this link https://github.com/sequelize/sequelize-auto. If you need further clarification on th ...

Show concealed elements above everything else

I've encountered an issue with my custom dropdown list as it displaces other elements when it appears. I want it to overlay on top of everything else, similar to the default select behavior. Despite trying to set position: relative; and z-index:100;, ...

Unable to connect to server using local IP address

Currently utilizing a freezer application () and encountering an issue where I can only access the server on localhost. I attempted to modify the settings.js file by replacing 127.0.0.1 with 0.0.0.0, rebuilt it, but it still persists on localhost. Even aft ...

Guide to implementing CSS3 transitions with prefixes using JavaScript

Is there a way to apply CSS styles using JavaScript when I don't have access to the CSS file? #fade div { -webkit-transition: opacity 1s; -moz-transition: opacity 1s; -o-transition: opacity 1s; -ms-transition: opacity 1s; transition: ...

Tips for sending custom props to a dynamic page in Next.js

I have created a component called Card.js which is responsible for linking to dynamic pages when a card is clicked. My goal is to pass a value, such as 'category', to the dynamic page [id].js so that I can implement additional logic there. Card. ...

Instructions for securing a React Front End with Node.js Express-Sessions authentication:

I have decided to move away from using Firestore auth in order to develop my own authentication system. Here is my goal: To create a React web app that allows users to sign up and sign in. Authenticated users should be able to interact with a REST API, w ...

Using Vue.js to set both v-model and v-bind:value on one input element

I have a React component that has a form for submitting user information. The main issue I'm facing is setting a default value in the input field. When the page loads, I want the input field to display the user's existing email address by defaul ...

Managing JSON data for multiple images with different dimensions

"images": { "options": [ { "size": "small", "dimensions": [ { "width": 100, "height": 75, "link": "https://i.vimeocdn.com/video/566955426_100x75.jpg?r=pad", ...

Error: The JavaScript SRC cheat is malfunctioning

Having an issue with the code below. The 'dummy1' and 'dummy2' variables are not loading their content as expected on the page. Any suggestions? <html> <head> <title>JavaScript On-line Test</title> <script LA ...

What is the process for creating instant notifications using AJAX, PHP, and MySQL?

I am looking to implement real-time notifications on my website and have already set up the notification bar: <div class="alert alert-info alert-with-icon" data-notify="container"> <button type="button" aria-hidden="true" class="close"> ...

Utilizing Axios to pass multiple values through a parameter as a comma-separated list

Desired query string format: http://fqdn/page?categoryID=1&categoryID=2 Axios get request function: requestCategories () { return axios.get(globalConfig.CATS_URL, { params: { ...(this.category ? { categoryId: this.category } : {}) } ...

I am unable to utilize third-party components within my Nuxt.js/vue.js project

I am attempting to use a library for my Nuxt project, following the guidelines laid out in the documentation available here: getting-started Despite following the instructions provided, I keep encountering errors such as "Unknown custom element: - did you ...

Having trouble with ejs.filters?

I'm having trouble grasping ejs filters and getting them to work correctly: Server.js var ejs = require('ejs'); ejs.filters.example = function() { //placeholder for example }; Routes.js app.get('/home', function(req, res) { ...

Double Marker Challenge in Brochure

I am currently using Leaflet in conjunction with VueJs. I have encountered an issue where a double marker is appearing at a specific location when I add a marker: The code responsible for this behavior is as follows: mounted() { this.map = L.ma ...

Automatically redirect to a different page upon clicking the jquery popup button

I integrated a jQuery popup feature on my website to display messages. Now, I am looking to implement a redirect to another page when the user clicks a button within the jQuery popup. However, I am unsure of how to achieve this. <script type="text/ja ...