Search code examples
javascriptreplacefetch-api

replace part of string in json in a fetch-response


I'm trying to replace part of a response before outputting it to a html document. Specifically I want to delete part of the response using replace.

fetch('https://api.foo.bar/5H2F8QXNTRW7P7LNL1KHXL76JQXXI2')
    .then(response => response.json())
    .then(json.replace(" and null Cent", "")) // trying to delete this part
    .then(json => document.getElementById("betrag").innerHTML = json)
    .catch(err => console.log('Request Failed', err));

It's been working fine until I tried to delete part of the response. The console shows

Uncaught ReferenceError: json is not defined

I'm not getting this error without the line trying to replace part of the response. I#m lost.

I tried json.replace and response.replace without success.


Solution

  • fetch('https://api.foo.bar/5H2F8QXNTRW7P7LNL1KHXL76JQXXI2')
        .then(response => response.json())
        .then(json => {
            // Convert the JSON object to a string to perform the replacement
            let jsonString = JSON.stringify(json);
    
            // Replace the specific part of the text
            jsonString = jsonString.replace(" and null Cent", "");
    
            // Parse the modified string back to a JSON object
            let modifiedJson = JSON.parse(jsonString);
    
            // Update the HTML element with the modified JSON data
            document.getElementById("betrag").innerHTML = modifiedJson;
        })
        .catch(err => console.log('Request Failed', err));