Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON string from fetch to object

Tags:

json

fetch-api

I need to convert my JSON response to an object, how can I achieve this?

My JSON response:

[  
   {  
      "id":296,
      "nama":"Appetizer"
   },
   {  
      "id":295,
      "nama":"Bahan"
   }
]
like image 708
Aditia Dananjaya Avatar asked Dec 01 '22 11:12

Aditia Dananjaya


2 Answers

Provided your response is a valid JSON, just do this

var obj = JSON.parse(response);
like image 88
anshulk Avatar answered Dec 05 '22 19:12

anshulk


You need to use JSON.parse in a try catch to catch errors if JSON is not valid.

let str = '[{"id":296,"nama":"Appetizer"},{"id":295,"nama":"Bahan"}]';

try {
  let obj = JSON.parse(str);
} catch (ex) {
  console.error(ex);
}

To convert back your object to string, use Stringify

JSON.stringify(obj)
like image 41
Ludovic Avatar answered Dec 05 '22 18:12

Ludovic