-
-
Save bettysteger/5299316 to your computer and use it in GitHub Desktop.
require 'rubygems' | |
require 'json/ld' | |
require 'net/http' | |
context = { | |
"foaf" => "http://xmlns.com/foaf/0.1/", | |
"dbo" => "http://dbpedia.org/ontology/", | |
"xsd" => "http://www.w3.org/2001/XMLSchema#", | |
"name" => { | |
"@id" => "foaf:name", | |
"@type" => "" | |
}, | |
"born"=> { | |
"@type" => "xsd:date", | |
"@id"=> "dbo:birthDate" | |
}, | |
"thumb" => "dbo:thumbnail", | |
"homepage" => "foaf:homepage" | |
} | |
id = "http://dbpedia.org/resource/Jim_Carrey" | |
response = Net::HTTP.get_response("dbpedia.org","/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=DESCRIBE+%3Chttp://dbpedia.org/resource/Jim_Carrey%3E&output=application%2Fld%2Bjson") | |
input = JSON.parse response.body | |
input = input["@id"] | |
compact = JSON::LD::API.compact(input, context) | |
jim_carrey = compact["@graph"].detect do |resource| | |
resource["@id"] == id | |
end | |
puts jim_carrey["name"] # {"@language"=>"en", "@value"=>"Jim Carrey"} | |
puts jim_carrey["born"].first # 1962-01-17 | |
puts jim_carrey["thumb"] | |
puts jim_carrey["homepage"] | |
# getting his movies | |
movies = compact["@graph"].map do |resource| | |
resource["@id"] if resource["dbo:starring"] == id | |
end | |
puts "---------------------------" | |
puts "Jim Carrey Movies:" | |
puts movies.compact! |
DBpedia already supports JSON-LD and AFAICT it's completely compliant to the latest version of JSON-LD. Here's the JSON-LD representation of Jim Carrey.
Unfortunately content negotiation doesn't work yet. Thanks for bringing this to my attention @lpsBetty. I'm already in contact with the people that run DBpedia to fix that.
thank you guys for replying!
i have already tried to compact with JSON-LD output, but it didn't worked as expected because i got the code wrong.. now i've got it right with a little bit guessing !?! , see updated gist ..
so i've updated the gist again with my own context!
and i now detect the resource of jim carrey and then print it out.. is this the right way to achieve this?
Good news.. DBpedia has been fixed. So as long as you set the right Accept headers and follow the redirect you get the data directly. You can try it with curl:
curl -LH "Accept: application/ld+json" http://dbpedia.org/resource/Jim_Carrey
I'll leave the rest to @gkellogg as he's the Ruby expert.
oh ok cool! thank you, maybe i'm gonna now try something in javascript ;)
If you define a @context mapping value to @value, you could avoid the gsub. YOU could then just pass an open file descriptor from Net::HTTP as the input argument to compact.
Note that DBPedia supports an earlier form of JSON-LD, I expect they'll update when the spec is done.
You could also get RDF from DBPedia and transform it to JSON; for querying, you're better to use their SPARQL interface.