I made a get request with HTTPoison, but now I'm trying to parse the JSON file. For that I'm using Poison library. But I'm having some problems to get an element from the JSON object.
Here my code :
def parse_json do
IO.puts("\nLet's parse JSON file.")
url = "https://entreprise.data.gouv.fr/api/sirene/v3/etablissements/?page=1&per_page=1&etat_administratif=A&denomination_usuelle=" <> "SAFENERGY"
start()
case get(url) do
{:ok, %{status_code: 200, body: body}} ->
IO.puts("Success research.")
decode!(body)
#|> Map.to_list() NON-FUNCTIONAL
#|> Enum.find(&match?(["etablissements" | _], &1)) NON-FUNCTIONAL
#|> Enum.find_value(fn %{"siren" => siren} -> siren end) NON-FUNCTIONAL
#|> IO.puts(&(&1.siren)) NON-FUNCTIONAL
|> IO.inspect()
{:ok, %{status_code: 404}} ->
IO.puts("None match between establishment's name and Sirene API.")
{:ok, %{status_code: 500}} ->
IO.puts("Nonfunctional Sirene API's server (maintenance...).")
{:ok, %{status_code: 429}} ->
IO.puts("Exceeding the maximum call volume (7 requests/s maximum).")
{:error, %{reason: reason}} ->
IO.puts("Failure research.")
IO.inspect(reason)
_ -> IO.puts("Unknown error! Good luck to find it!")
end
end
My output:
%{
"etablissements" => [
%{
"statut_diffusion" => "O",
"libelle_voie" => "MAS DES PERES",
"distribution_speciale_2" => nil,
"geo_ligne" => "G",
"libelle_voie_2" => nil,
"unite_legale_id" => 33014385,
"type_voie_2" => nil,
"geo_type" => "street",
"code_postal_2" => nil,
"libelle_pays_etranger" => nil,
"indice_repetition_2" => nil,
"libelle_commune" => "MAUGUIO",
"siret" => "48944519700036",
"id" => 70725092,
"distribution_speciale" => nil,
"indice_repetition" => nil,
"siren" => "489445197",
"complement_adresse" => nil,
"unite_legale" => %{
"statut_diffusion" => "O",
"nic_siege" => "00036",
"prenom_usuel" => nil,
"sigle" => nil,
"denomination" => "SAFENERGY",
"id" => 33014385,
"pseudonyme" => nil,
"nom_usage" => nil,
"siren" => "489445197",
"date_dernier_traitement" => "2019-11-13T15:06:19",
"annee_effectifs" => nil,
"categorie_entreprise" => "PME",
"tranche_effectifs" => nil,
"identifiant_association" => nil,
"sexe" => nil,
"prenom_2" => nil,
"caractere_employeur" => "N",
"nom" => nil,
"created_at" => "2020-07-02T02:56:19.773+02:00",
"economie_sociale_solidaire" => "N",
"prenom_4" => nil,
"date_fin" => nil,
"date_debut" => "2019-07-01",
"prenom_3" => nil,
"date_creation" => "2006-04-01",
"annee_categorie_entreprise" => "2017",
"denomination_usuelle_2" => nil,
"denomination_usuelle_3" => nil,
"denomination_usuelle_1" => nil,
...
},
"date_dernier_traitement" => "2019-11-13T15:06:19",
"annee_effectifs" => nil,
"denomination_usuelle" => "SAFENERGY",
"code_pays_etranger" => nil,
"complement_adresse_2" => nil,
"tranche_effectifs" => nil,
"enseigne_1" => nil,
"numero_voie_2" => nil,
"geo_id" => "34154_b163",
"activite_principale_registre_metiers" => nil,
"geo_l5" => nil,
"caractere_employeur" => "N",
"geo_l4" => "MAS DES PERES",
"nic" => "00036",
"code_postal" => "34130",
"libelle_cedex_2" => nil,
"created_at" => "2020-07-02T03:12:45.814+02:00",
"numero_voie" => "9002",
"longitude" => "3.967449",
"type_voie" => nil,
"date_debut" => "2019-07-01",
"code_cedex_2" => nil,
"date_creation" => "2019-07-01",
"code_commune_2" => nil,
"libelle_pays_etranger_2" => nil,
"libelle_commune_etranger" => nil,
"latitude" => "43.603798",
"code_cedex" => nil,
"geo_score" => "0.95",
...
}
],
"meta" => %{
"page" => 1,
"per_page" => 1,
"total_pages" => 1,
"total_results" => 1
}
}
Like you can see above (four lines in comments), I'm trying to extract "siren" element for instance but it failed... Am I off the mark ?
Use Access in general and Kernel.get_in/2 here in particular
body
|> decode!()
|> get_in(["etablissements", Access.all(), "unite_legale", "siren"])
#⇒ "0"
With Access you might filter the outcome on each step, get all branches, etc. Here we use Access.all/0 to get to all elements of the list.
I guess you want to iterate over all "etablissements" and retrieve all SIREN numbers. You can try something like:
body
|> decode!()
|> Map.get("etablissements")
|> Enum.map(fn etablissement -> Map.get(etablissement, "siren") end)
assuming the data structure is the one shown above. Notice that Enum.map/2 is not related to the Map module, but runs the function fn etablissement -> Map.get(etablissement, "siren") end on each entry of the "etablissements" list.
This should return a list with all SIREN numbers. If there might be duplicate entries, you can use Enum.uniq/1.
Related
In Shopware 6 I still try to get the product into the System using the API.
I now get a product, but it has no price, despite the fact, that I inserted it.
That actually results in a product without a price and stops the backend from loading the products, so I have to manually change the price using the export, edit, and then import method.
The product object gets encoded with json_encode as well before sending that as a request to the API.
I can't seem to find out what's wrong with the following code:
$price = [
"currencyId" => "b7d2554b0ce847cd82f3ac9bd1c0dfca",
"net" => $net,
"gross" => $gross,
"linked" => false
];
$price = json_encode($price);
$product = [
"id" => str_replace("-","", $productId),
"productId" => str_replace("-","", $productId),
"name" => $name,
"taxId" => $taxId,
"productNumber" => $productNumber,
"minPurchase" => $minPurchase,
"price" => $price,
"purchasePrice" => $purchasePrice,
"stock" => $stock,
"images" => $images,
"atributes" => $atributes,
"categoryId" => "7997459a37f94a75a14d7cbd872a926f"
];
I had to write the code like this:
$product = [
"id" => str_replace("-","", $productId),
"productId" => str_replace("-","", $productId),
"parentId" =>str_replace("-","", "4307a3d9afee4b46b3da1a8fc6230db5"),
"name" => $name,
"taxId" => $taxId,
"productNumber" => $productNumber,
"minPurchase" => $minPurchase,
"price" => [[
"currencyId" => "b7d2554b0ce847cd82f3ac9bd1c0dfca",
"net" => $net,
"gross" => $price,
"linked" => true
]],
"purchasePrice" => $purchasePrice,
"stock" => $stock,
"description" => $description,
"images" => $images,
"atributes" => $atributes,
"categoryId" => "7997459a37f94a75a14d7cbd872a926f"
];
I want to download all photo from channel. Try to use https://github.com/danog/MadelineProto to get channel message history:
$MadelineProto->messages->getHistory([
'peer' => "-100xxxxxx",
'offset_id' => 0,
'offset_date' => 0,
'add_offset' => 0,
'limit' => 25,
'max_id' => 1000,
'min_id' => 0,
'hash' => 1,
]);
As a result I get an array of messages with media:
array(13) {
["_"] => string(7) "message"
["out"] => bool(false)
["mentioned"] => bool(false)
["media_unread"] => bool(false)
["silent"] => bool(false)
["post"] => bool(false)
["id"] => int(38)
["from_id"] => int(500100000)
["to_id"] => array(2) {
["_"] =>string(11) "peerChannel"
["channel_id"] =>int(1369700000)
}
["date"] => int(1520150410)
["message"] => string(0) ""
["media"] => array(2) {
["_"] =>string(17) "messageMediaPhoto"
["photo"] =>array(6) {
["_"] => string(5) "photo"
["has_stickers"] => bool(false)
["id"] => int(5251753100000000000)
["access_hash"] => int(-6118957000000000000)
["date"] => int(1520150405)
["sizes"] => array(4) {
[0] =>array(6) {
["_"] => string(9) "photoSize"
["type"] => string(1) "s"
["location"] => array(5) {
["_"] =>string(12) "fileLocation"
["dc_id"] =>int(2)
["volume_id"] =>int(235100000)
["local_id"] =>int(250000)
["secret"] =>int(5193339136300000000)
}
["w"] => int(90)
["h"] => int(67)
["size"] => int(1078)
}
....
Now I want to download this file and didnt known how do it. Method https://core.telegram.org/bots/api#getfile request file_id but I havent it.
Message history only give me this photo parameters:
id
access_hash
dc_id
volume_id
local_id
secret
How can I get file_id or generate it from available data?
Or how can I download photo from channel history by another way?
MadelineProto has undocumented functions like download_to_file or download_to_dir.
$MadelineProto->download_to_dir($message['media'], $pathtodir)
Controller:
#sites = Site.inspections_enabled_controllers_search.search("test")
#sites.each do |s|
if s == nil
puts "WHAT THE ...?"
end
ap s #print out the site
end
Model:
has_many :inspections_enabled_controllers,
:class_name => 'Controller',
:conditions => ['controllers.inspections_enabled = ?', true]
sphinx_scope(:inspections_enabled_controllers_search) {
{
:joins => :inspections_enabled_controllers
}
}
Returns:
#<Site:0x000000114618b8> {
:id => 156,
:name => "Test Site"
}
WHAT THE ...?
nil
WHAT THE ...?
nil
WHAT THE ...?
nil
#<Site:0x000000111c41a0> {
:id => 213,
:name => "TestRail V1.5 - SmartLine"
}
WHAT THE ...?
nil
WHAT THE ...?
nil
WHAT THE ...?
nil
WHAT THE ...?
nil
#<Site:0x00000011461200> {
:id => 220,
:name => "Activation Testing"
}
NOTICE the total of SEVEN "-" which are simply empty items in an array.
This worked for me
#sites = Site.inspections_enabled_controllers_search.search("test", :retry_stale => 1)
Reference:
http://pat.github.com/ts/en/searching.html#nils
Is there any easy way to include the multiupload feature to NetzkeFormView or GridView(AddInForm)?
My current image uloading field with carrierwave is:
{:name => :image_link, :xtype => :displayfield, :display_only => true, :getter => lambda { |r| %Q(<a href='#{r.image.url}'>Download</a>) if r.image.url }},
{:name => :image, :field_label => "Upload image", :xtype => :fileuploadfield, :getter => lambda { |r| "" }, :display_only => true}
brand new to MongoDB / mongoid and still pretty green on ruby / rails
on the rails console:
t = Task.all(:conditions => {:title => "task2"})
=> #<Mongoid::Criteria
selector: {:title=>"task2"},
options: {},
class: Task,
embedded: false>
>> t.first
=> #<Task _id: 4d7e2cdb73ec3227dd000009, title: "task2", latitude: 23.987904829, longitude: -12.9423875, created_by: "4d792d6973ec3248e3000001">
returns what I would expect, but
t = Task.where(:created_by => "4d792d6973ec3248e3000001")
=> #<Mongoid::Criteria
selector: {:created_by=>BSON::ObjectId('4d792d6973ec3248e3000001')},
options: {},
class: Task,
embedded: false>
>> t.first
=> nil
same result with:
t = Task.all(:conditions => {:created_by => "4d792d6973ec3248e3000001"})
here is the model:
class Task
include Mongoid::Document
field :title
field :latitude, :type => Float
field :longitude, :type => Float
field :created_by
end
what am I doing wrong ?
updated example:
>> Task.new(:title => "task8", :created_by => "4d792d6973ec3248e3000001")
=> #<Task _id: 4d81037973ec32cc22000003, latitude: nil, longitude: nil, title: "task8", created_by: "4d792d6973ec3248e3000001">
>> t = Task.all(:conditions => {:created_by => "4d792d6973ec3248e3000001"})
=> #<Mongoid::Criteria
selector: {:created_by=>BSON::ObjectId('4d792d6973ec3248e3000001')},
options: {},
class: Task,
embedded: false>
>> t.first
=> nil
do I need to specifically define created_by as :type => String ?
Looks like created_by is stored as a string in your document, but then you query looking for an ObjectId. ObjectId's and strings aren't the same.
Try changing
>> Task.new(:title => "task8", :created_by => "4d792d6973ec3248e3000001")
to
>> Task.new(:title => "task8", :created_by => BSON::ObjectId("4d792d6973ec3248e3000001"))
You have to include this functionality in mongoid as explained in docs:
class Person
include Mongoid::Document
include Mongoid::Timestamps
end