Compare exact result in Javascript/Jquery - javascript

I'm just about creating a website, where im iterating through a list of items in a JSON file. It looks like this:
"prices" : [
{
"market_hash_name" : "★ Bayonet",
"price" : 141.04,
"created_at" : 1455877920
},
{
"market_hash_name" : "AWP | Pit Viper (Minimal Wear)",
"price" : "1.83",
"created_at" : 1455878005
}
.
.
. and so on
Now, i'm sucessfull in searching and picking the "price" by the "market_hash_name" with a $ajax and a $each function in combination by jquery. Here it is:
$.ajax({url: "../json/priceapi.json", success: function(result){ // Get JSON File
$.each(result.prices, function(i, v) {
if (v.market_hash_name == market_hash_name) { ... // Parse JSON Data
Everything works fine, the code seems to be alright, but the problem is, that there, anywhere in this huge JSON File is a exact same second "market_hash_name" but with a additional text part. An exmaple:
{
"market_hash_name" : "Souvenir AWP | Pit Viper (Minimal Wear)",
"price" : "102.18", // Additional text "Souvenir"
"created_at" : 1455878414
},
Due this "double tag" the $each function tells me, that there are two results, for one key. I only want to have the exact result. Do you have any ideas how to do that? Is there a way to do something like this?
$.each(result.prices, function(i, v) {
if (v.market_hash_name - "Souvenir" == market_hash_name) { ...

Thanks to briosheje! https://jsfiddle.net/briosheje/f68wfet6/1/ works nice! Takes a bit, but i works :)
var res = {
"prices": []
};
$.each(json.prices, function(i, e) {
var exists = false;
$.each(res.prices, function (c, f){
console.log(f.market_hash_name + " <> " + e.market_hash_name);
console.log(f.market_hash_name == e.market_hash_name);
if (("Souvenir " + f.market_hash_name) == e.market_hash_name) {
exists = true;
}
});
!exists && res.prices.push(e);
});
console.log(res);

Related

Need to search API output in JSON format for value and print entire array content

I have googlesheets functions that parse json and import to sheets, you can find the code for the function in ImportJson file.
function IMPORTJSON(url,xpath){
try{
// /rates/EUR
var res = UrlFetchApp.fetch(url);
var content = res.getContentText();
var json = JSON.parse(content);
var patharray = xpath.split("/");
//Logger.log(patharray);
for(var i=0;i<patharray.length;i++){
json = json[patharray[i]];
}
//Logger.log(typeof(json));
if(typeof(json) === "undefined"){
return "Node Not Available";
} else if(typeof(json) === "object"){
var tempArr = [];
for(var obj in json){
tempArr.push([obj,json[obj]]);
}
return tempArr;
} else if(typeof(json) !== "object") {
return json;
}
}
catch(err){
return "Error getting data";
}
}
The functions is pretty simple and self explanatory . Disclosure I got this function from here. "https://www.youtube.com/watch?v=EXKhVQU37WM"
I had some additional requirements that this function cannot do. Need to search API output in JSON format for value and print entire array content.
For example I had a JSON output as below .
{
"symbol" : "AAPL",
"historicalDCF" : [ {
"date" : "2019-03-30",
"Stock Price" : 190.5064,
"DCF" : 199.51439324614452
}, {
"date" : "2018-12-29",
"Stock Price" : 156.4638,
"DCF" : 165.25974241335186
}, {
"date" : "2018-09-29",
"Stock Price" : 224.6375,
"DCF" : 233.0488839004929
}, {
"date" : "2018-06-30",
"Stock Price" : 184.3734,
"DCF" : 192.36145120758877
}, {
"date" : "2018-03-31",
"Stock Price" : 163.5502,
"DCF" : 172.0839412239145
}, {
"date" : "2017-12-30",
"Stock Price" : 168.339,
"DCF" : 178.05212237708827
}, {
"date" : "2017-09-30",
"Stock Price" : 149.7705,
"DCF" : 160.23613044781487
}, {
"date" : "2017-07-01",
"Stock Price" : 139.1847,
"DCF" : 150.3852802404117
}, {
"date" : "2017-04-01",
"Stock Price" : 138.8057,
"DCF" : 148.7456306248566
}, {
"date" : "2016-12-31",
"Stock Price" : 111.7097,
"DCF" : 120.02897160465633
}, {
"date" : "2016-09-24",
"Stock Price" : 108.0101,
"DCF" : 116.70616209306208
}
]
}
You can also check live version of this API on this link " https://financialmodelingprep.com/api/v3/company/historical-discounted-cash-flow/AAPL?period=quarter"
To get DCF value on "2019-03-30", I can simply use functions as this:
=IMPORTJSON("https://financialmodelingprep.com/api/v3/company/historical-discounted-cash-flow/AAPL?period=quarter","historicalDCF/0/DCF")
What if I need to search through date and get the value of Stock Price? For example I need to get the value of Stock price and DCF on this date "2017-09-30" . How could I do it without knowing array position ?
So for this I need help either by creating new function or modifying existing function to get this functionality.
Help is highly appreciated and thanks in advance to all the gurus out there.
json.historicalDCF.filter((el) => el.date === "2017-07-01") will return the object that matches that date.
You could get the return like:
function findByDate(dateParam) {
return json.historicalDCF.filter((el) => el.date === dateParam)
}
var theInfoIWantVariable = findByDate("2017-1-1-make-sure-this-is-a-string")
Given that your IMPORT function is returning a JSON object (and assuming the format is what you've shown in your post), then you could simply use a regular javascript filter() function to get the specific date you want:
const data =IMPORTJSON("https://financialmodelingprep.com/api/v3/company/historical-discounted-cash-flow/AAPL?period=quarter","historicalDCF");
// now, data is the JSON array containing the historical data. All the data. We can filter it for whatever we want.
const myOneDayRecord = data.find( record => record.date === '2016-03-30' );
// so the variable myOneDayRecord is the specific record by date we wanted. Now we can use it as a normal javascript object.
console.log(`So on ${myOneDayRecord.date}, the stock price was ${myOneDayRecord["Stock Price"] } and the DCF was ${myOneDayRecord.DCF}`);
// note that, in the above line,I had to use bracket notation to get to the 'Stock Price' property. That's because of the space in the property name.
If I understood you correctly, you want to create a custom function that will:
Accept a url, a xpath and a date as a parameter.
Call IMPORTJSON and pass the previous url and xpath as parameters.
In the JSON returned by IMPORTJSON, find the item in historicalDCF whose date matches the one passed as a parameter.
Return its corresponding Stock Price.
If all of the abose is correct, then you could do something along the following lines:
function GETSTOCKPRICE(url, xpath, date) {
var jsonData = IMPORTJSON(url,xpath);
var historical = jsonData["historicalDCF"];
var stockPrice;
for (var i = 0; i < historical.length; i++) {
if (historical[i]["date"] === date) {
stockPrice = historical[i]["Stock Price"];
break;
}
}
return stockPrice;
}
And then, you can use this function in your sheet by passing it the correct parameters. For example, if you want to get the stock price corresponding to 2017-09-30:
=GETSTOCKPRICE("https://financialmodelingprep.com/api/v3/company/historical-discounted-cash-flow/AAPL?period=quarter", "historicalDCF/0/DCF", "2017-09-30")
Notes:
Methods like filter or find, arrow functions and declarations like const won't work here, since Apps Script doesn't currently support ES6.
You could also modify GETSTOCKPRICE so that it only accepts date as a parameter, and the call to IMPORTJSON has its parameters hard-coded (this would make sense if you're always going to use IMPORTJSON for this exact url and xpath). But that's up to you.
I hope this is of any help.

MongoDB, PHP and JavaScript

I have the following document in a MongoDB 2.0.4 and PHP 5.5*
{
"children" : [
{
"name" : "openGL::gl"
},
{
"name" : "openGL::interfaces"
},
{
"name" : "openGL::picking"
},
{
"name" : "openGL::objects"
}
],
"name" : "test"
}
Using php I want to create another collection having a copy of this document.Because I cannot use php mongo::command I am just getting a cursor for the first collection and insert this cursor into the second:
$cursor = $collection->find();
foreach($cursor as $document){
$result->insert($document);
};
$collection is the original and $result is the new one.
Now the strange thing is sometimes this works perfectly and sometimes I recieve the following:
{
"children" : {
"3" : {
"name" : "openGL::objects"
},
"0" : {
"name" : "openGL::gl"
},
"1" : {
"name" : "openGL::interfaces"
},
"2" : {
"name" : "openGL::picking"
}
},
"name" : "test"
}
And this is really bad because I am trying to get those infos into Javascript and therefore the first one (the original) is an Array whereas the second one is an object with properties.
Does somebody know why I get this and how to fix it?
So this is the solution I am using now!
$db->command(array(
"eval" => new MongoCode("function(){
db['".$toCopy."'].copyTo('".$newName."')
};"
)
));
You can copy a collection on the server with the .copyTo() method for the collection:
db.collection.copyTo("new")
There is no client transfer as there is currently being done by iterating.
If for some reason you want this to be a part of your code then there is the "runCommand" option which has a longer syntax. So in PHP code, do the longer version of this with "eval":
$db->command(array(
"eval" => new MongoCode("function(){ " .
"db.collection.find().forEach(function(doc) { " .
"db.newcollection.insert(doc); " .
"}); " .
"};"
);
));
That will run the copy on the server. Take care to read the documentation and warnings on db.eval(). And aside from all else, but much the same as you were doing, then you must re-create all indexes on the target collection that you want to use.
But in general this will be a better way than iterating over a client connection.
Have you tried to sort the cursor like:
$cursor = $collection->find();
$cursor = $cursor->sort(array('name_of_key_variable' => 1)); //sorts in ascending order
foreach($cursor as $doc) {
...
}
You might also try more of the MongoCursor options listed here:
http://www.php.net/manual/en/class.mongocursor.php at the table of contents

jQuery how to use $.getJSON or $.ajax with Google Maps (and without jQuery)

Newb having trouble with simple task of querying Google Maps for the distance between two cities.
Really, a first learning attempt to get JSON data and make use of it.
I googled a ton, and read many related answers here on SO, first. (Though I eventually found the main answer here.)
I pasted all the code, along with comments about what I was thinking, hoping that someone could explain what I was missing, in beginner terms.
The main problem is that I'm getting the data with one of the two methods I tried ($.ajax, but not $.getJSON, though I thought both would work), see Console Output at the very end of the code, but I couldn't figure out how to actually grab/use the data. Specifically, in the multi-nested object/array combo, I was trying to get the "text" in "distance" in "legs" in "routes" in the "responseText" that was returned.
[edit:] Ok, I finally found an existing SO question, that was [enough to figure it out] (How can I get the object in JSON using jquery or javascript)
In hindsight, I should have just kept looking through even more existing answers.
I'm not sure whether to leave, delete or erase, but I'll edit a bit and leave for now, because there are still parts of the question that are confusing, including:
How to use $.getJSON, in the code below -- shouldn't that work, too?
How to know exactly what part of the overall JSON object to use as the argument in the $.parseJSON() method;
Why you still have to use $.parseJSON if you can see your object outputted, and it looks like the object/array combination already. See comments, below.
<!DOCTYPE html>
<html>
<head>
<title>City Distances</title>
<script src="js/jquery.min.js"></script>
</head>
<body>
<input type="text" id="city1" value="Atlanta"><br/>
<input type="text" id="city2" value="Orlando"><br/>
<button type="submit" id="btn">Submit</button>
<script>
var city1 = document.getElementById('city1');
var city2 = document.getElementById('city2');
var btn = document.getElementById('btn');
var valCities = [];
function getCities () {
valCities[0] = city1.value;
valCities[1] = city2.value;
var gMap = "http://maps.googleapis.com/maps/api/directions/json?origin=" + valCities[0] + "&destination=" + valCities[1] + "&sensor=false";
// I'm confused about what $.getJSON is supposed to get.
// Here's why I was trying to get the JSON data. I never saw how this would work; no idea.
var b = $.getJSON(gMap);
// Is the data I'm looking for in here, somewhere?
// I thought there'd be something like the c['responseText'], below.
// (I numbered each element (g), b/c I thought I could access with [#] bracket notation).
var g = 0;
for (var i in b) {
console.log("$.getJSON: <" + g + "> [" + i + "]: " + b[i]);
g += 1;
};
// jQuery method (I found more examples that used this method, so I tried this, too.)
// I'm confused by the example showing the argument 'json' being passed in, b/c I didn't
// use it.
// But c['responseText'] seemed to have the "distance" data I needed.
var c = $.ajax({
type: "GET",
url: gMap,
dataType: "json",
success: function(json) {
// I'm trying to see what was gotten. Added counter for the elements; I
// thought maybe I could access with bracket notation using the number of
// the element.
// The relevant output is listed, below, in comment at end of script.
console.log("\n $.ajax success: \n")
var h = 0;
for (var j in c) {
console.log("$.ajax: <" + h + "> c[" + j + "]: " + c[j]);
h += 1;
}
** This is what finally worked **
// nested objects and arrays...
var d = c['responseText'];
var jsonObject = $.parseJSON(d);
var theDistance = jsonObject.routes[0].legs[0].distance.text;
console.log("*** theDistance: " + theDistance + "\n\n ***");
Or was it that I should use .map like this?
Anyway, here's the the rest, mostly just for the console.log output at the end:
// **And if this works, and prints out all the data:
var d = c['responseText']; // (from above)
console.log("ddd: " + d);
/* This is what it prints to the console:
ddd: {
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 33.74932270,
"lng" : -81.37924350
},
"southwest" : {
"lat" : 28.47414120,
"lng" : -84.40452560
}
},
"copyrights" : "Map data ©2013 Google",
"legs" : [
{
"distance" : {
"text" : "442 mi",
"value" : 710661
},
*/
// **Then why doesn't this work? (It says routes is undefined.)
console.log(d.routes[0].legs[0].distance.text);
}
});
}
// Event handler for the little form (which already has the two demo cities, pre-populated.
btn.addEventListener("click", getCities, false);
/*
** OUTPUT **
This is the relevant JSON data returned from Google from the console.log, above.
[Console output:]
. . .
$.ajax: <18> c[responseText]: {
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 33.74932270,
"lng" : -81.37924350
},
"southwest" : {
"lat" : 28.47414120,
"lng" : -84.40452560
}
},
"copyrights" : "Map data ©2013 Google",
"legs" : [
{
"distance" : {
** --- This is what I was trying to get --- **
**"text" : "442 mi",**
"value" : 710661
},
"duration" : {
"text" : "6 hours 13 mins",
"value" : 22360
},
"end_address" : "Orlando, FL, USA",
"end_location" : {
"lat" : 28.53831440,
"lng" : -81.37924350
},
"start_address" : "Atlanta, GA, USA",
"start_location" : {
"lat" : 33.74883970,
"lng" : -84.38750639999999
*/
</script>
</body>
</html>

Insert correct arrays doesn't work

Well, now i am getting "has to be an array", before it had to be a string.
Can someone help me out of this problem? Check comments.
function publishPhoto() {
var tags = []; var x,y=0;
if ( harBilled == 0 ) {
if ( profilSendt==0) {
var c =0;
//Get the online friends from array!
for ( i=0;i<globalTags.length;i++){
if ( c < 49 ){ //max 50 tags!
tags.push({"tag_uid": ""+globalTags[i]+"",
"x" : ""+(Math.floor(Math.random() * 309) + 1)+"",
"y" : ""+(Math.floor(Math.random() * 309) + 1)+""
});
}
c = c+1;
}
var newJson = new String(array2json(tags));
newJson = newJson.toString();
FB.api('me/photos', 'post', {
message: txt2send,
status: 'success',
url: 'http://meedies.com/0bcf1f22_smush_400x400.jpeg',
}, function (response) {
if (!response || response.error) {
harBilled=0;
alert(var_dump(response.error));
} else {
var fi = response.id;
alert("Now this!");
FB.api(fi + '/tags?tags='+tags, 'POST', function(response){
alert(var_dump(response));
});
harBilled=1;
//getPages()
}
})
profilSendt=1;
}
}
I am trying to insert multiple ids to be tagged on a picture. Can something help me though this correctly
Sounds like you're filling the wrong type of data into the tags array.
Try this...
var tags = [
{"tag_uid": 91839404, "x": 250,"y": 350},
{"tag_uid": 91839401, "x": 220,"y": 340}
];
Edit
Just insert the objects itself and not an array with one single object.
tags.push({"tag_uid": 91839404, "x": 250,"y": 350});
This is the Facebook definition:
PHOTO_ID/tags?tags=[{"id":"1234", "X":1, "y":2}, {"id":"12345", "x":1, "y":2}]
I've just tried to do that with json_encode. The result was:
[{"id":"1","x":"1","y":"2"},{"id":"2","x":"1","y":"2"}]
To post your variable tags, use
console.log(tags);
Doesn't work on old IE browsers.
It's still an array. If the api requires it as string, you'll have to encode it. Like I said, json encoding would return exactly the same "visual" result, except - it would be a string, not an array.
[{"tag_uid": 587908880,"x" : 17,"y" : 251},{"tag_uid": 664099777,"x" : 166,"y" : 197},{"tag_uid": 824600788,"x" : 275,"y" : 89},{"tag_uid": 1012286173,"x" : 247,"y" : 225},{"tag_uid": 1027953684,"x" : 81,"y" : 25},{"tag_uid": 1049653245,"x" : 169,"y" : 2},{"tag_uid": 1089472771,"x" : 236,"y" : 125},{"tag_uid": 1157692807,"x" : 75,"y" : 70},{"tag_uid": 1183641328,"x" : 307,"y" : 254},{"tag_uid": 1206853982,"x" : 154,"y" : 254},{"tag_uid": 1279891790,"x" : 54,"y" : 5},{"tag_uid": 1379771663,"x" : 206,"y" : 280},{"tag_uid": 1446366514,"x" : 37,"y" : 168},{"tag_uid": 1599969496,"x" : 26,"y" : 226},{"tag_uid": 1645141964,"x" : 250,"y" : 23},{"tag_uid": 100000830101385,"x" : 5,"y" : 110},{"tag_uid": 100003711738950,"x" : 174,"y" : 294},{"tag_uid": 100003908889022,"x" : 249,"y" : 38}]
Once the string is formated, you may send it this way:
PHOTO_ID/tags?tags=[{"id":"1234"}, {"id":"12345"}]
Here, you're converting your array to json (I'll assume it's converted correctly)
var newJson = new String(array2json(tags));
newJson = newJson.toString();
But here, you're still using the array
FB.api(fi + '/tags?tags='+tags
I think i've found your problem:
The x and y coordinates that you're using, should be as percentage offset from the left(x) and top(y). Allowed values are 0 - 100. As of your posts below, I see that some of the coordinates exceed the 100 limit. You should probably recalculate your coordinates as relative offsets. But for first, try it with some test data, to see if it works.
Also, see documentation.
Try this, a tell me, how it's gone.

How to read JSON(server response) in Javascript?

I am sending some request on a server and it's reply me this:
{"COLUMNS":["REGISTRATION_DT","USERNAME","PASSWORD","FNAME","LNAME","EMAIL","MOBILE","FACEBOOK_ID"],"DATA":[["March, 17 2012 16:18:00","someuser",somepass,"somename","somesur","someemail",sometel,"someid"]]}
I tried a lot but nothing seems to working for me!
var xml2 = this.responseData;
var xml3 = xml2.getElementsByTagName("data");
Ti.API.log(xml3.FNAME);
For this code I get "null".
Any help would be appreciated!
If you're trying to use JSON format, your problem is that the data within the [...] also needs to be in pairs, and grouped in {...} like here.
For instance,
{
"sales": [
{ "firstname" : "John", "lastname" : "Brown" },
{ "firstname" : "Marc", "lastname" : "Johnson" }
] // end of sales array
}
So you might have:
{"COLUMNS": [
{"REGISTRATION_DT" : "19901212", "USERNAME" : "kudos", "PASSWORD" : "tx91!#1", ... },
{"REGISTRATION_DT" : "19940709", "USERNAME" : "jenny", "PASSWORD" : "fxuf#2", ... },
{"REGISTRATION_DT" : "20070110", "USERNAME" : "benji12", "PASSWORD" : "rabbit19", ... }
]
}
If the server is sending you something which you refer to as res, you can just do this to parse it in your Javascript:
var o=JSON.parse(res);
You can then cycle through each instance within columns like follows:
for (var i=0;i<o.COLUMNS.length;i++)
{
var date = o.COLUMNS[i].REGISTRATION_DT; ....
}
see that link. READ JSON RESPONSE
It's perfect.
JSON objects work just like any normal javascript objects or dictionaries
// You can do it this way
var data = this.responseData["DATA"]
// Or this way
var data = this.responseData.DATA
In your case, COLUMNS and data are both arrays, so it looks like you're trying to get the element from data that corresponds to the "FNAME" element in COLUMNS?
var columns = this.responseData["COLUMNS"];
var data = this.responseData["DATA"][0];
for(var i=0; i<columns.length; i++){
if(columns[i] == "FNAME"){
Ti.API.log(data[i]);
}
}
EDIT: If you can't change the data on the server end, you can make your own object client side. This also helps if you have to refer to multiple columns (which you probably do).
var columns = this.responseData["COLUMNS"];
var data = this.responseData["DATA"][0];
var realData = {};
for(var i=0; i<columns.length; i++){
realData[columns[i]] = data[i];
}
// Now you can access properties directly by name.
Ti.API.log(data.FNAME);
More edit:
My answers only consider the first row in DATA, because I misread originally. I'll leave it up to you to figure out how to process the others.
If you got here trying to find out how to read from [Response object] (as I did) -
this what can help:
- if you use fetch don't forget about res.json() before logging in console
fetch(`http://localhost:3000/data/${hour}`, {
method: 'get'
})
.then(res => {
return res.json()
})
.then((response) => {
console.log('res: ' + JSON.stringify(response))
})
Testing out your code in http://jsonlint.com/, it says that your server's response is not a valid JSON string.
Additionally, I recommend checking out jQuery.parseJSON http://api.jquery.com/jQuery.parseJSON/
Just use JSON.parse(serverResponse)

Categories

Resources