-1

I have an API response in string

"{"div":{"display": "flex","flexDirection": "column","alignItems":"center","fontFamily":"Helvetica Neue"},"a":{"fontSize": 16, "textAlign": "center","fontWeight":"bold","color":"#324F85"},"p":{"fontSize": 34,"textAlign":"center","color": "#7f8f96d"},"h5": {"fontWeight": "normal","fontSize": 18,"textAlign":"center"}}"

I want to convert the string to object like

{div:{display: 'flex',flexDirection: 'column',alignItems: 'center',fontFamily:'Helvetica Neue'},a: {fontSize: 16,textAlign: 'center',fontWeight: 'bold',color: '#324F85'}, p:{fontSize: 34,textAlign: 'center',color: '#7f8f96d6'},h5: { fontWeight: 'normal',fontSize: 18,textAlign: 'center'}}
ajay 24
  • 304
  • 3
  • 13
  • 1
    Does this answer your question? [Converting a string to JSON object](https://stackoverflow.com/questions/10976897/converting-a-string-to-json-object) – Kordrad Aug 18 '21 at 11:11
  • @Kordrad not exactly applicable, since OP has invalid JSON. – VLAZ Aug 18 '21 at 11:12
  • @VLAZ why its invalid ? – ajay 24 Aug 18 '21 at 11:14
  • JSON requires keys and string values to be in double quotes. Your data uses single quotes. – VLAZ Aug 18 '21 at 11:15
  • @VLAZ i have updated question (data in double quotes) still its giving Error: Unexpected identifier – ajay 24 Aug 18 '21 at 11:29
  • Because the outer quotes are also double. Your string is terminated early. Look at the syntax highlighting and you'll see it's not all just one string. Whatever you are doing in order to produce the JSON *you should fix that* to produce valid JSON. Currently, it seems you're just trying to match some sort of valid syntax by hand. There are plenty of tools that will generate JSON for you. – VLAZ Aug 18 '21 at 11:31

1 Answers1

0

This can be done with the JSON.parse() function like so:

const apiResponseAsObject = JSON.parse(apiResponseAsString)

For future questions, please format your code as actual code.