Compare Json Response to Json text File - ruby

I have a file text.json and I have an JSON HTTP response. What's a good to check if they are equal?
Here's what I have but I think there's a better solutions.
JSON.parse(response["data"]).eql?(File.read(text.json))

You need to parse both ends of your test:
JSON.parse(response["data"]).eql?(JSON.parse(File.read(text.json)))
Edit
If you want to test an array of JSONs, and you are not sure that the order will be the same in the file meaning [{a:1, b:2}, {a:2, b:1}] should equal [{a:2, b:1}, {a:1, b:2}], you'll need to sort them first (see here for more techniques):
JSON.parse(response["data"]).sort.eql?(JSON.parse(File.read(text.json)).sort)
Edit 2
Since Hashes don't sort well, the above won't work. You could use one of the other techniques:
from_response = JSON.parse(response["data"])
from_file = JSON.parse(File.read(text.json))
(from_response & from_file) == from_response
(from_response - from_file).empty?

Related

IMPORTXML To Return a Value from dividendhistory.org

I want to return the value of "Yield:" from a series of stocks from a URL dividenhistory.org, for example HDIF into a Google sheet using IMPORTXML, where F7 represents the user supplied ticker.
=IMPORTXML("https://dividendhistory.org/payout/TSX/"&F7, "/html/body/div/div[2]/div[2]/p[4]")
The problem with the above is the yield value is not always located in the same paragraph, depending on the ticker. It also returns with the word "Yield:" as part of the value.
I believe I should be using the XPATH parameter which should find and return the yield value only, but I am lost. I am open to all suggestions!
I tried with a few of the tickers there, and this should work. For example:
=IMPORTXML("https://dividendhistory.org/payout/ctas/", "//p[contains(.,'Yield')]/text()")
Output:
Yield: 1.05%
Obviously, you can change 'ctas' for any user input.
Try this and see if it works on all tickers.
EDIT:
To get only the number 1.05, you need to split the result and output the 2nd part:
=index(split(IMPORTXML("https://dividendhistory.org/payout/ctas/", "//p[contains(.,'Yield')]/text()"), ": "),2)
Output:
0.0105

What's the correct way to read an array from a csv field in Ruby?

I am trying to save some class objects to a csv file, everything works fine. I can save and read back from the csv file, there is only a 'minor' problem with an attribute that is an Array of Strings.
When I save it to the file it appears like this: "[""Dan Brown""]"
CSV.open('documents.csv', "w") do |csv|
csv << %w[ISBN Titre Auteurs Type Disponibilité]
#docs.each { |doc|
csv << [doc.isbn, doc.titre, doc.auteurs, doc.type, doc.empruntable ? "Disponible" : "Emprunté"]
}
end
And when I try to extract the data from the file I end up with something like this: ["[\"Dan Brown\"]"].
table = CSV.parse(File.read("documents.csv"), headers: true)
table.each do |row|
doc = Document.new(row['Titre'], row['ISBN'], row['Type'])
doc.auteurs << row['Auteurs'] #This the array where there is a 'problem'
if row['Disponibilité'] == "Disponible"
doc.empruntable = true
else
doc.empruntable = false
end
#docs.push(doc) #this an array where I save my objects
end
I tried many things to solve this but without any luck. I would be thankful if you can help me find a solution.
Since a CSV file, by it's nature, contains in its fields only strings, not arrays or other data types, the CSV class is applying the to_s method of the objects to turn them into a string before putting them into the CSV.
When you later read them back, you just get this - the string representation of what once had been your array. The only one who knows that 'Auteurs' should end up as an array of strings, is the application, i.e. you.
Hence on reading the CSV, after having extracted the autheurs string, you need to convert it manually back to an Array, because there is no automatic "inverse method" to reverse the to_s.
A cheap, but dangerous way to do it, is to use eval, which indeed would reconstruct your array. However, you need to be sure that nobody had a chance to fiddle manually with the CSV data, because an eval allows sneaking in arbitrary code.
A safer way would be to either write your own conversion function to and from String representation, or use a format such as YAML or JSON for representing the Array as String, instead of using to_s.

Cypress - counting number of elements in an array that contain a specific string

Attempting to confirm that of all the schema in the head of a page exactly 3 of them should have a specific string within them. These schemas have no tags or sub classes to differentiate themselves from each other, only the text within them. I can confirm that the text exists within any of the schema:
cy.get('head > script[type="application/ld+json"]').should('contain', '"#type":"Product"')
But what I need is to confirm that that string exists 3 times, something like this:
cy.get('head > script[type="application/ld+json"]').contains('"#type":"Product"').should('have.length', 3)
And I can't seem to find a way to get this to work since .filter, .find, .contains, etc don't filter down the way I need them to. Any suggestions? At this point it seems like I either need to import a custom library or get someone to add ids to these specific schema. Thanks!
The first thing to note is that .contains() always yields a single result, even when many element match.
It's not very explicit in the docs, but this is what it says
Yields
.contains() yields the new DOM element it found.
If you run
cy.get('head > script[type="application/ld+json"]')
.contains('"#type":"Product"')
.then(console.log) // logs an object with length: 1
and open up the object logged in devtools you'll see length: 1, but if you remove the .contains('"#type":"Product"') the log will show a higher length.
You can avoid this by using the jQuery :contains() selector
cy.get('script[type="application/ld+json"]:contains("#type\": \"Product")')
.then(console.log) // logs an object with length: 3
.should('have.length', 3);
Note the inner parts of the search string have escape chars (\) for quote marks that are part of the search string.
If you want to avoid escape chars, use a bit of javascript inside a .then() to filter
cy.get('script[type="application/ld+json"]')
.then($els => $els.filter((index, el) => el.innerText.includes('"#type": "Product"')) )
.then(console.log) // logs an object with length: 3
.should('have.length', 3);

Converting multiple arrays into a single hash

I'm working on a configuration file parser and I need help parsing key: value pairs into a hash.
I have data in the form of: key: value key2: value2 another_key: another_value.
So far I have code in form of
line = line.strip!.split(':\s+')
which returns an array in the form of
["key:value"]["key2: value2"]["another_key: another_value"]
How can I turn these arrays into a single hash in the form of
{key=>value, key2=>value2, another_key=>another_value}
I'm not sure if the key:value pairs need to be in the form of a string or not. Whatever is easiest to work with.
Thanks for your help!
This is the solution I found:
line = line.strip.split(':')
hash = Hash[*line]
which results in the output{"key"=>"value"}, {"key2"=>"value2"}
Very very close to Cary's solution:
Hash[*line.delete(':').split]
Even simpler:
Hash[*line.gsub(':',' ').split]
# => {"key"=>"value", "key2"=>"value2", "another_key"=>"another_value"}
Assuming the key and value are single words, I'd probably do something like this:
Hash[line.scan(/(\w+):\s?(\w+)/)]
You can change the regex if it's not quite what you are looking for.

How do I extract a value from this Ruby hash?

I'm using the Foursquare API, and I want to extract the "id" value from this hash
[{"id"=>"4fe89779e4b09fd3748d3c5a", "name"=>"Hitcrowd", "contact"=>{"phone"=>"8662012805", "formattedPhone"=>"(866) 201-2805", "twitter"=>"hitcrowd"}, "location"=>{"address"=>"1275 Glenlivet Drive", "crossStreet"=>"Route 100", "lat"=>40.59089895083072, "lng"=>-75.6291255071468, "postalCode"=>"18106", "city"=>"Allentown", "state"=>"Pa", "country"=>"United States", "cc"=>"US"}, "categories"=>[{"id"=>"4bf58dd8d48988d125941735", "name"=>"Tech Startup", "pluralName"=>"Tech Startups", "shortName"=>"Tech Startup", "icon"=>"https://foursquare.com/img/categories/shops/technology.png", "parents"=>["Professional & Other Places", "Offices"], "primary"=>true}], "verified"=>true, "stats"=>{"checkinsCount"=>86, "usersCount"=>4, "tipCount"=>0}, "url"=>"http://www.hitcrowd.com", "likes"=>{"count"=>0, "groups"=>[]}, "beenHere"=>{"count"=>0}, "storeId"=>""}]
When I try to extract it by using ['id'], I get this error can't convert Symbol into Integer. How do I extract the value using ruby? Also, how do I do this for multiple hashes extracting the "id" value each time?
Please pardon my inexperience. Thanks!
It's wrapped in an array, that's what the [ and ] mean on the start and end. But it also looks like this array only one object in it, which is the hash you really want.
So assuming you want the first object in this array:
mydata[0]['id'] # or mydata.first['id'] as Factor Mystic suggests
But usually when an API returns an Array there is a reason (it might return many results instead of just one), and naively plucking the first item from it my not be what you want. So be sure you are getting the kind of data you really expect before hard coding this into your application.
For multiple hashes, if you want to do something with the id (run a procedure of some kind) then
resultsArray.each do |person|
id = person["id"] #then do something with the id
end
If you want to just get an array containing the ids then
resultsArray.map{|person| person["id"]}
# ["4fe89779e4b09fd3748d3c5a", "5df890079e4b09fd3748d3c5a"]
To just grab the one item from the array, see Alex Wayne's answer
To get an array of ids, try: resultsArray.map { |result| result["id"] }

Resources