JSON-LD example
This example shows how to decouple frontend code from JSON key names of the backend data.
by Angelo Veltens
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsonld/0.4.12/jsonld.min.js"></script>
<div id="view">
</div>
JavaScript
const personDataFromBackend = {
"@context": {
"@vocab": "https://schema.org/",
"firstname": "givenName",
"lastname": "familyName",
"birthDay": "birthDate",
"id": "@id"
},
"id": "42",
"firstname": "John",
"lastname": "Doe",
"birthDay": "1978-05-17"
}
const context = {
"@vocab": "https://schema.org/",
first_name: "givenName",
last_name: "familyName",
birth_date: "birthDate",
person_id: "@id"
}
jsonld.compact(personDataFromBackend, context, (err, person) => {
view.textContent = greet(person);
});
function greet(person) {
return `Hello, ${person.first_name} ${person.last_name}`;
}