0

I made a script to retrieve data from an API and show it in HTML. The problem is that the API answers with something like that

[{"seen":"2021-08-24 04:13:51"}]

And I want the user to see something like

2021-08-24 04:13:51

How can i modify this text inside of javascript? (The output is variable but the number of characters is always the same, idk if this is a useful info...)

1
  • 2
    you need to put a bit more effort into how to access array and obj. And pls post your questions adding what you tried, where are you stuck. No one will write the code for you. Commented Sep 2, 2021 at 11:03

3 Answers 3

2

What you have to do is set innerText value from the JSON. You can access the value using response[0].seen

const response = [{"seen":"2021-08-24 04:13:51"}];
console.log(response[0].seen);
document.getElementById('lastupdatedon').innerText = response[0].seen;
<p id="lastupdatedon"></p>

Sign up to request clarification or add additional context in comments.

Comments

1

The server is returning data in json format, you need to parse the response to a javascript object and then you can use the value as you want

const theServerResponse = '[{"seen":"2021-08-24 04:13:51"}]'

const parsedResponse = JSON.parse(theServerResponse)


//At this point you can get that value
parsedResponse[0].seen

Comments

1

Use below script

                var fromAPI='[{"seen":"2021-08-24 04:13:51"}]';
                var data=JSON.parse(fromAPI);
                if(data!=null && data.length>0)
                {
                    document.getElementById('lastupdatedon').innerText = data[0].seen;
                }

HTML

<h3 id="lastupdatedon"></h3>

Do not forget to check for nulls, index is greater than 0. IF server doesnt return data then your app will throw an error of undefined.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.