How to modify text in Javascript - javascript

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...)

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>

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

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.

Related

Using Jquery to get numeric value which is in between "/" in link

I am trying to fetch numeric value from link like this.
Example link
/produkt/114664/bergans-of-norway-airojohka-jakke-herre
So I need to fetch 114664.
I have used following jquery code
jQuery(document).ready(function($) {
var outputv = $('.-thumbnail a').map(function() {
return this.href.replace(/[^\d]/g, '');
}).get();
console.log( outputv );
});
https://jsfiddle.net/a2qL5oyp/1/
The issue I am facing is that in some cases I have urls like this
/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre
Here I have "3" inside text string, so in my code I am actually getting the output as "11466433" But I only need 114664
So is there any possibility i can get numeric values only after /produkt/ ?
If you know that the path structure of your link will always be like in your question, it's safe to do this:
var path = '/produkt/114664/bergans-of-norway-airojohka-jakke-herre';
var id = path.split('/')[2];
This splits the string up by '/' into an array, where you can easily reference your desired value from there.
If you want the numerical part after /produkt/ (without limitiation where that might be...) use a regular expression, match against the string:
var str = '/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre';
alert(str.match(/\/produkt\/(\d+)/)[1])
(Note: In the real code you need to make sure .match() returned a valid array before accessing [1])

Get values from JSON returned data

So I have a function that makes an ajax call and returns a json string. I am having trouble trying to access the values that I need, below is my code of what I have and a few examples of what I have tried.
s.search().then(function (specials) {
var returnJSON = JSON.parse(specials[0]);
var x = returnJSON.location.x;
var y = returnJSON.location.y;
});
When I check the dev tools I'm getting the following error.
JSON.parse: unexpected character at line 1 column 2 of the JSON data
Here is the the JSON returned value after I stringify it.
[{"feature":{"geometry":{"type":"point","x":-82.9172080701955,"y":42.55426092899978,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Postal","Match_addr":"48035, Clinton Township, Michigan","StAddr":"","City":"Clinton Township","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-82.922209,"ymin":42.549261,"xmax":-82.912209,"ymax":42.559261,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"48035, Clinton Township, Michigan"},{"feature":{"geometry":{"type":"point","x":-84.03589825899667,"y":44.826904141314174,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton Twp, Michigan","StAddr":"","City":"Clinton Twp","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-84.085899,"ymin":44.776904,"xmax":-83.985899,"ymax":44.876904,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton Twp, Michigan"},{"feature":{"geometry":{"type":"point","x":-83.93987906956261,"y":42.065412162742234,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton Twp, Michigan","StAddr":"","City":"Clinton Twp","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-83.98988,"ymin":42.015412,"xmax":-83.88988,"ymax":42.115412,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton Twp, Michigan"},{"feature":{"geometry":{"type":"point","x":-82.93354923650725,"y":42.60054198222781,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton Twp, Michigan","StAddr":"","City":"Clinton Twp","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-82.98355,"ymin":42.550542,"xmax":-82.88355,"ymax":42.650542,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton Twp, Michigan"},{"feature":{"geometry":{"type":"point","x":-83.97095926895429,"y":42.07240087260328,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton, Michigan","StAddr":"","City":"Clinton","score":94.29},"infoTemplate":null},"extent":{"type":"extent","xmin":-84.02096,"ymin":42.022401,"xmax":-83.92096,"ymax":42.122401,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton, Michigan"},{"feature":{"geometry":{"type":"point","x":-84.6015125489642,"y":42.943655651388326,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"SubAdmin","Match_addr":"Clinton, Michigan","StAddr":"","City":"Clinton","score":94.29},"infoTemplate":null},"extent":{"type":"extent","xmin":-84.839514,"ymin":42.705656,"xmax":-84.363514,"ymax":43.181656,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton, Michigan"}]
I am trying to access candidates location x value and y value.
There are some Strings in your JSON on separate lines. When you copy and paste your JSON in a linter (e.g.: json linter), you will see the errors.
EDIT:
You edited your question so you are now using valid JSON.
There is no need to parse your JSON when you already have valid JSON. You can just select the correct keys. Looking at your JSON, you can select your x and y like this:
var returnJSON = specials[0];
var x = returnJSON.feature.geometry.x;
var y = returnJSON.feature.geometry.y;
Checkout this codepen for an example.
You don't need to "parse" JSON returned from a service usually. It is already a Javascript object in the then callback.
s.search().then(function (specials) {
var firstItem = specials[0];
var x = firstItem.location.x;
var y = firstItem.location.y;
});
It should be noted, however, that the first item that comes back in your array of specials does not have a property location accoring to the JSON example you posted.
Perhaps you were after firstItem.feature.geometry.x, but im not sure.

filtering object so that only certain links are accepted

I'm trying to filter urls I grabbed using json but the code is not working
$.each(data.next, function(z,item){
JSON.stringify(item.data.url);
var url =item.data.url;
if (url.substring(0,11)=='http://youtub'){
var x = '<p>' + url + '</p>'; //this line and the one after that is just to put it in html
$(x).appendTo("#text");
}
});
Where did I make the error? I've never used stringify before so is that it?
Have you try actually using the variable return by JSON.stringify?
var url = JSON.stringify(item.data.url);
JSON.stringify doesn't modify the argument it is given, it return a converted format
See documentation
Also I am not sure why would anyone want to convert an easy to iterate over object into a string to build a filter. If anything a well build object would make filtering a bliss.

Parse response using Jquery

I have to parse a response from the server,
The response is like..
[4,"1.0",1368544417760]
[1,"Great West Road","222",1368544595000]
[1,"Ruislip Manor Station","114",1368544479000]
[1,"Bank Station / Threadneedle Street","26",1368544731000]
[1,"Belvue School","E10",1368545955000]
[1,"Brunel Road","283",1368544706000]
[1,"Annesley Avenue","303",1368545930000]
[1,"Brixton Station Road","35",1368545854000]
[1,"Southampton Row","91",1368545537000]
[1,"Camden Road Station","29",1368545008000]
[1,"Fulham Cemetery","74",1368545210000]
The response doesn't seem to like JSON or XML.
Please help me know how to parse such type of response using Jquery.
I have to update the DOM based on the response and the response is getting updated
at a regular interval automatically.
The first number may be an indicator of what sort of data is in the rest of the "array".
I'd say
parse each line as if it were JSON. It'll turn into a javascript array.
var array = JSON.parse(oneLine); // Many browsers support this.
Then pull the bits out and put them into a proper object by name. (How to do that depends on the 1st element, perhaps.)
var obj = {};
if (array[0] == 1) {
obj.station = obj[1];
obj.number = obj[2];
obj.timestamp = obj[3]; // guessing what this is, too.
}
Do whatever you need with the data object.
Put all that in a loop. Repeat until done.
There is a similar Stack Overflow question here --> converting CSV/XLS to JSON?
Looks like there are a few different possible solutions that you could look at.

Can I access a hash stored in html elements data attribute with jquery?

I've got several html elements that I'm appending hashes to like so:
<p class='message' data-dependencies={'#first':{'equal':'Yes'}}>
Relevant Content
</p>
so that
$(".message").first().data("dependencies")
returns
{'#first':{'equal':'Yes'}}
But as a buddy just pointed out to me, this value is a string. So naturally the filter described below has a hard time with it.
The goal of the filter is to be able to grab elements that have a specified key, in this case "#first".
$el.children().find("*").filter(function(){
var dependency_hash = $(this).data("dependencies");
if(dependency_hash != undefined && "#first" in dependency_hash){
return true
}
});
Is there a way to access the hash as passed via the data object or is there another way I can structure the data so as to accomplish the same means of being able to select elements based on the key?
If you store it as valid JSON, you can parse it, and get is content.
<p class='message' data-dependencies='{"#first":{"equal":"Yes"}}'>
Relevant Content
</p>
var json = $(".message").first().attr("data-dependencies");
// HTML5 browsers
// var json = document.querySelector(".message").dataset.dependencies;
var parsed = $.parseJSON(data);
alert(parsed["#first"].equal); // "Yes"
Or if you use jQuery's .data(), it will parse it automatically.
var parsed = $(".message").first().data("dependencies");
alert(parsed["#first"].equal); // "Yes"
Use JSON.parse. There are polyfills if you need support in older browsers.
$el.children().find("*").filter(function(){
var dependency_hash = $(this).data("dependencies");
var parsed_hash = JSON.parse(dependency_hash);
if(parsed_hash != undefined && "#first" in parsed_hash ){
return true
}
});
You probably want to serialize your data as JSON http://json.org/ and then get it back in JS.
You can use jquery's parser http://api.jquery.com/jQuery.parseJSON/

Categories