Tags down


javascript convert string to an object

By : sunil patil
Date : May 06 2020, 08:40 AM

I'm have two variable with data and DataConvert I try to convert data like DataConvert

let data="{'one':{'id':'2'},'one':{'id':'2'}}"
let DataConvert={'one':{'id':'2'},'one':{'id':'2'}}


Answer :

The only built-in function that will do it with eval() function :

let data="{'one':{'id':'2'},'two':{'id':'2'}}";
let DataConvert;
eval(`DataConvert = ${data}`);


In your jsfiddle you have \r\n inside some of the strings, which is not valid JavaScript. If you want those to be kept literally in the result, you need to escape them before calling eval():

data = data.replace(/\r/g, '\\r').replace(/\n/g, '\\n');

But this is dangerous if you don't control the source of the string, since it will execute arbitrary expression in data.

If you change the quotes to double quotes, you can use JSON.parse(), which is safer.

let data='{"one":{"id":"2"},"two":{"id":"2"}}';
let DataConvert = JSON.parse(data);


Note :object keys have to be unique, you can't have two properties named "one". I changed the second one to "two" to make it valid.

Share : facebook icon twitter icon
Related Posts Related Posts :
  • clear array after form submit
  • pass url variable to javascript
  • access data using api
  • div position fixed css
  • add horizontal line between two div
  • disable toggle button css
  • css fixed line height
  • background image not working
  • table cell border
  • text line break css
  • overlay div on div
  • text direction rtl css
  • bind inner div click to outer div
  • jquery ajax oncomplete
  • how to use promise in for loop
  • jquery get element using variable
  • javascript send textbox value
  • pass div class content to another class or id
  • css new line after element
  • css calc not working properly
  • link disabled jquery
  • sql join table to subquery
  • MS Access SQL Issue with OR AND Operators
  • set textarea value using php
  • php merge two arrays into one
  • php form with google captcha
  • update current row in php
  • php date format mysql
  • mysql pdo select query
  • php function return an array
  • PHP mysqldump database to sql file
  • display image query
  • php create array using foreach loop
  • associative array php
  • group_concat in mysql laravel
  • php array_push empty
  • mysql on update cascade not working
  • pdo insert prepared statement
  • mysql insert ignore vs on duplicate key
  • mysql insert into existing row
  • mysql multi insert query
  • mysql group by show all rows
  • php change profile image
  • combine multiple arrays into one array php
  • how to sum values in an array
  • how to get sum of the total time
  • How to Create Facebook live stream without notification using API ?
  • on button click make div visible
  • css affect another element on hover
  • insert line after paragraph word
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org