xpath or Defiant.js and getting node information - javascript

I have my json:
{
"data": {
"header": {
"version": 1,
"last_updated": "2015-09-16T14:09:22Z"
},
"frequent" : {
"keywords": [
{
"keyword":"roi",
"keyword":"subjectrecord",
"keyword":"evidence",
"keyword":"case",
"keyword":"account",
"keyword":"supervisor",
"keyword":"legacy tecs"
}
]
},
"body": {
"items": [
{
"item": {
"type": "pdf",
"title": "title 1",
"updated_time": "2015-09-16T14:09:22Z",
"keywords": [
{
"keyword":"supervisor"
},
{
"keyword":"manager"
},
{
"keyword":"title 1"
}
]
}
},
{
"item": {
"type": "pdf",
"title": "title 2",
"updated_time": "2015-09-16T14:09:22Z",
"keywords": [
{
"keyword":"supervisor"
}
]
}
},
{
"item": {
"type": "pdf",
"title": "title 3",
"updated_time": "2015-09-16T14:09:22Z"
}
}
]
}
}
}
What i want to be able to do is search "body" and return any items where a match occurs with the keyword. So for instance, if I search "supervisor" my results should look like:
"item": {
"type": "pdf",
"title": "title 1",
"updated_time": "2015-09-16T14:09:22Z",
"keywords": [
{
"keyword":"supervisor"
},
{
"keyword":"manager"
},
{
"keyword":"title 1"
}
]
}
},
{
"item": {
"type": "pdf",
"title": "title 2",
"updated_time": "2015-09-16T14:09:22Z",
"keywords": [
{
"keyword":"supervisor"
}
]
}
}
Doing the following only returns the keyword.
var results = JSON.search(potentials, '//*[keyword="'+query+'"]');

put /.. at the end of the query
var results = JSON.search(potentials, '//*[keyword="'+query+'"]/..');

Related

How to update a value in a complex fhirBundle JSON?

Given a bewildering fhir document like https://raw.githubusercontent.com/Notarise-gov-sg/api-notarise-healthcerts/master/test/fixtures/v2/pdt_art_with_nric_unwrapped.json
I need to update the part the JSON from { "id": "NRIC-FIN", "value": "S9098989Z" } to { "id": "NRIC-FIN", "value": "foobar" } and then emit the whole JSON again with that change.
I just about know how to access the value.
const fs = require("fs");
let rawdata = fs.readFileSync("pdt_art_with_nric_unwrapped.json");
let art = JSON.parse(rawdata);
let nric = art.fhirBundle.entry
.flatMap((entry) => entry.resource)
.find((entry) => entry.resourceType === "Patient")
.identifier.find((entry) => entry.id === "NRIC-FIN").value;
console.log(nric);
Though I am puzzled how to update this value since it's so difficult to access. Am I missing a trick? I don't want to use regex btw!
You seem to be very close - why not just set .value using the syntax you already have...?
const fs = require("fs");
let rawdata = fs.readFileSync("pdt_art_with_nric_unwrapped.json");
let art = JSON.parse(rawdata);
let nric = art.fhirBundle.entry
.flatMap((entry) => entry.resource)
.find((entry) => entry.resourceType === "Patient")
.identifier.find((entry) => entry.id === "NRIC-FIN").value = 'foobar';
console.dir(art.fhirBundle.entry)
... results in:
[
{
"fullUrl": "urn:uuid:ba7b7c8d-c509-4d9d-be4e-f99b6de29e23",
"resource": {
"resourceType": "Patient",
"extension": [
{
"url": "http://hl7.org/fhir/StructureDefinition/patient-nationality",
"extension": [
{
"url": "code",
"valueCodeableConcept": {
"text": "Patient Nationality",
"coding": [
{
"system": "urn:iso:std:iso:3166",
"code": "SG"
}
]
}
}
]
}
],
"identifier": [
{
"id": "PPN",
"type": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "PPN",
"display": "Passport Number"
}
]
},
"value": "E7831177G"
},
{
"id": "NRIC-FIN",
"value": "foobar"
}
],
"name": [
{
"text": "Tan Chen Chen"
}
],
"gender": "female",
"birthDate": "1990-01-15"
}
},
{
"fullUrl": "urn:uuid:7729970e-ab26-469f-b3e5-36a42ec24146",
"resource": {
"resourceType": "Observation",
"specimen": {
"type": "Specimen",
"reference": "urn:uuid:0275bfaf-48fb-44e0-80cd-9c504f80e6ae"
},
"performer": [
{
"type": "Practitioner",
"reference": "urn:uuid:3dbff0de-d4a4-4e1d-98bf-af7428b8a04b"
},
{
"id": "LHP",
"type": "Organization",
"reference": "urn:uuid:fa2328af-4882-4eaa-8c28-66dab46950f1"
}
],
"identifier": [
{
"id": "ACSN",
"type": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "ACSN",
"display": "Accession ID"
}
]
},
"value": "123456789"
}
],
"category": [
{
"coding": [
{
"system": "http://snomed.info/sct",
"code": "840539006",
"display": "COVID-19"
}
]
}
],
"code": {
"coding": [
{
"system": "http://loinc.org",
"code": "97097-0",
"display": "SARS-CoV-2 (COVID-19) Ag [Presence] in Upper respiratory specimen by Rapid immunoassay"
}
]
},
"valueCodeableConcept": {
"coding": [
{
"system": "http://snomed.info/sct",
"code": "260385009",
"display": "Negative"
}
]
},
"effectiveDateTime": "2020-09-28T06:15:00Z",
"status": "final"
}
},
{
"fullUrl": "urn:uuid:0275bfaf-48fb-44e0-80cd-9c504f80e6ae",
"resource": {
"resourceType": "Specimen",
"subject": {
"type": "Device",
"reference": "urn:uuid:9103a5c8-5957-40f5-85a1-e6633e890777"
},
"type": {
"coding": [
{
"system": "http://snomed.info/sct",
"code": "697989009",
"display": "Anterior nares swab"
}
]
},
"collection": {
"collectedDateTime": "2020-09-27T06:15:00Z"
}
}
},
{
"fullUrl": "urn:uuid:3dbff0de-d4a4-4e1d-98bf-af7428b8a04b",
"resource": {
"resourceType": "Practitioner",
"name": [
{
"text": "Dr Michael Lim"
}
],
"qualification": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "MCR",
"display": "Practitioner Medicare number"
}
]
},
"identifier": [
{
"id": "MCR",
"value": "123456"
}
],
"issuer": {
"type": "Organization",
"reference": "urn:uuid:bc7065ee-42aa-473a-a614-afd8a7b30b1e"
}
}
]
}
},
{
"fullUrl": "urn:uuid:bc7065ee-42aa-473a-a614-afd8a7b30b1e",
"resource": {
"resourceType": "Organization",
"name": "Ministry of Health (MOH)",
"type": [
{
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/organization-type",
"code": "govt",
"display": "Government"
}
]
}
],
"contact": [
{
"telecom": [
{
"system": "url",
"value": "https://www.moh.gov.sg"
},
{
"system": "phone",
"value": "+6563259220"
}
],
"address": {
"type": "physical",
"use": "work",
"text": "Ministry of Health, 16 College Road, College of Medicine Building, Singapore 169854"
}
}
]
}
},
{
"fullUrl": "urn:uuid:fa2328af-4882-4eaa-8c28-66dab46950f1",
"resource": {
"resourceType": "Organization",
"name": "MacRitchie Medical Clinic",
"type": [
{
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/organization-type",
"code": "prov",
"display": "Healthcare Provider"
}
],
"text": "Licensed Healthcare Provider"
}
],
"contact": [
{
"telecom": [
{
"system": "url",
"value": "https://www.macritchieclinic.com.sg"
},
{
"system": "phone",
"value": "+6561234567"
}
],
"address": {
"type": "physical",
"use": "work",
"text": "MacRitchie Hospital, Thomson Road, Singapore 123000"
}
}
]
}
},
{
"fullUrl": "urn:uuid:9103a5c8-5957-40f5-85a1-e6633e890777",
"resource": {
"resourceType": "Device",
"type": {
"coding": [
{
"system": "https://covid-19-diagnostics.jrc.ec.europa.eu/devices",
"code": "1232",
"display": "Abbott Rapid Diagnostics, Panbio COVID-19 Ag Rapid Test"
}
]
}
}
}
]
... clearly showing foobar set as you seem to desire. (Feel free to test with this Repl.it).
To "emit the full JSON" again you would just re-stringify it:
let fullJSON = JSON.stringify(art);
Instead of traversing the object manually you can use library like Jsonpath:
function replace() {
data = JSON.parse(data);
jsonpath.apply(data,
'$.fhirBundle.entry[?(#.resource.resourceType == "Patient")].resource.identifier[?(#.id == "NRIC-FIN")].value',
function(value) {
document.body.innerHTML += `value=${value}<br>`;
return 'foobar';
});
document.body.innerHTML += `updated JSON:<br> <pre>${JSON.stringify(data, undefined, 2)}</pre`;
}
let data =
`{
"id": "340139b0-8e92-4ed6-a589-d54730f52963",
"version": "pdt-healthcert-v2.0",
"type": "ART",
"validFrom": "2021-08-24T04:22:36.062Z",
"fhirVersion": "4.0.1",
"fhirBundle": {
"resourceType": "Bundle",
"type": "collection",
"entry": [
{
"fullUrl": "urn:uuid:ba7b7c8d-c509-4d9d-be4e-f99b6de29e23",
"resource": {
"resourceType": "Patient",
"extension": [
{
"url": "http://hl7.org/fhir/StructureDefinition/patient-nationality",
"extension": [
{
"url": "code",
"valueCodeableConcept": {
"text": "Patient Nationality",
"coding": [
{ "system": "urn:iso:std:iso:3166", "code": "SG" }
]
}
}
]
}
],
"identifier": [
{
"id": "PPN",
"type": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "PPN",
"display": "Passport Number"
}
]
},
"value": "E7831177G"
},
{ "id": "NRIC-FIN", "value": "S9098989Z" }
],
"name": [{ "text": "Tan Chen Chen" }],
"gender": "female",
"birthDate": "1990-01-15"
}
},
{
"fullUrl": "urn:uuid:0275bfaf-48fb-44e0-80cd-9c504f80e6ae",
"resource": {
"resourceType": "Specimen",
"subject": {
"type": "Device",
"reference": "urn:uuid:9103a5c8-5957-40f5-85a1-e6633e890777"
},
"type": {
"coding": [
{
"system": "http://snomed.info/sct",
"code": "697989009",
"display": "Anterior nares swab"
}
]
},
"collection": { "collectedDateTime": "2020-09-27T06:15:00Z" }
}
}
]
},
"issuers": [
{
"id": "did:ethr:0xE39479928Cc4EfFE50774488780B9f616bd4B830",
"revocation": { "type": "NONE" },
"name": "SAMPLE CLINIC",
"identityProof": {
"type": "DNS-DID",
"location": "donotverify.testing.verify.gov.sg",
"key": "did:ethr:0xE39479928Cc4EfFE50774488780B9f616bd4B830#controller"
}
}
],
"$template": {
"name": "HEALTH_CERT",
"type": "EMBEDDED_RENDERER",
"url": "https://healthcert.renderer.moh.gov.sg/"
}
}`
replace();
<script src="https://cdn.jsdelivr.net/npm/jsonpath#1.1.1/jsonpath.min.js"></script>
If you are flat out replacing values without any other logic, and in case if you decide to use RegEx, then you can use String.replace().
let data =
`{ "identifier": [
{
"id": "PPN",
"type": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "PPN",
"display": "Passport Number"
}
]
},
"value": "E7831177G"
},
{ "id": "NRIC-FIN", "value": "S9098989Z" }
],
"name": [{ "text": "Tan Chen Chen" }],
"gender": "female",
"birthDate": "1990-01-15"
}
}`
let targetId = 'NRIC-FIN';
let find = new RegExp(`(?<=${targetId}.*value":\\s*").*?(?=")`, 'ig');
data = data.replace(find, 'foobar');;
document.write(`<pre>${data}</pre>`);
Note: In the regular expression, I have used i flag for case insensitive search. Used g flag to replace all occurrences of the id. If the id is unique and there is going to be only one occurrence in entire .json file then don't use g flag.

Exclude items from Array.map()

I am trying to exclude items that contain Packages in packageData.type. To show only the packageData that has items with packageData.type as Add-on.
Array is as example
{
"packageData": [
{
"title": "Title 1",
"type": [
"Packages"
]
},
{
"title": "Title 2",
"type": [
"Add-on"
]
},
{
"title": "Title 3",
"type": [
"Add-on"
]
},
{
"title": "Title 4",
"type": [
"Add-on"
]
}
]
}
and this is how I am currently trying to remove results which is giving zero results.
<ul>
{packageData.map(function() {
if (packageData.type ==! "Packages") {
return (
<li key={packageData.id}>
<a>
<img src={packageData.heroImage.sizes.src} alt=""/>
<h3>{packageData.title}</h3>
</a>
</li> );
} else {
return null;
};
})}
</ul>
How can I make this work? Or should I be filtering these results prior to displaying and then map the returned items?
You have to use filter before map, Filter will filter the array and then map will iterate through array. Below is the sample code
var data = {
"packageData": [
{
"title": "Title 1",
"type": [
"Packages"
]
},
{
"title": "Title 2",
"type": [
"Add-on"
]
},
{
"title": "Title 3",
"type": [
"Add-on"
]
},
{
"title": "Title 4",
"type": [
"Add-on"
]
}
]
};
data.packageData.filter((item) => { return item.type[0] !== 'Packages' }).map((item)=> { console.log(item); });

How do I join multiple columns into one in footable?

I have a FooTable that gets a part number returned as 3 separate cells. I'd like to combine them into one cell but I'm unsure of how the formatter and parser work for FooTable. my table html is just an empty table, everything is handledin the javascript. How would I go about doing this?
$(document).ready(function() {
jQuery(function($){
$('.table').footable({
"expandFirst": false,
"columns": [
{ "name": "PartID", "title":"PartID", "visible":false },
{"formatter": function(value){
return //I'm thinking this is where the code would go to join the next 3 columns? in the format ##.###.##
}},
{ "name": "PartCategory", "title": "PC" },
{ "name": "PartNumber1", "title": "PN1" },
{ "name": "PartNumber2", "title": "PN2", },
{ "name": "PartName", "title": "Name", },
{ "name": "DescShort", "title": "Description", },
{ "name": "SupplierName", "title": "Supplier", },
{ "name": "SupplierPartNumber", "title": "Supplier Part #", }
],
"rows": $.getJSON("../dist/scripts/testGetParts.php")
});
});
});
You can simply add data-hide="all" to the first two columns of those three:
{ "name": "", "title": "", data-hide="all"},
{ "name": "", "title": "", data-hide="all"},
{ "name": "Part Info", "title": "Part Information" }
Merge those in php (which you are good at) and just show them in here as one col in your dataset and Voila.
The simpler version if you can change the dataset is to not add those columns at all.
Another option if you cannot/don't want to change your server side code is to get the data and change it js and then bind them to rows afterwards.
var rows = $.getJSON("../dist/scripts/testGetParts.php");
foreach(row in rows) {
//merge those cols here in the third one
}
And then:
jQuery(function($){
$('.table').footable({
"expandFirst": false,
"columns": [
{ "name": "PartID", "title":"PartID", "visible":false },
{ "name": "PartCategory", "title": "PC", data-hide="all" },
{ "name": "PartNumber1", "title": "PN1", data-hide="all"},
{ "name": "Part Info", "title": "Part information" },
{ "name": "PartName", "title": "Name", },
{ "name": "DescShort", "title": "Description", },
{ "name": "SupplierName", "title": "Supplier", },
{ "name": "SupplierPartNumber", "title": "Supplier Part #", }
],
"rows": rows
});
});
Not sure how you do it persay in footable, in kendo you would do it like so.
$(document).ready(function() {
jQuery(function($){
$('.table').footable({
"expandFirst": false,
"columns": [
{ "name": "PartID", "title":"PartID", "visible":false },
{ "title":"PartNumber", formatter: function(data){
return data.PartCategory +"."+ data.PartNumber1 +"." + PartNumber2;
}},
{ "name": "PartName", "title": "Name", },
{ "name": "DescShort", "title": "Description", },
{ "name": "SupplierName", "title": "Supplier", },
{ "name": "SupplierPartNumber", "title": "Supplier Part #", }
],
"rows": $.getJSON("../dist/scripts/testGetParts.php")
});
});
});

Passing function argument to retrieve data from an object

I am have some trouble with a script I am working on. I have been provided with an object with multiple items from a product catalog.
What I am trying to do is to write a function which to which will allow me to render this data easily.
<script type="application/javascript">
SKUinfo =
{
"s238554": {
"Age": {
"Description": "Age 18+",
"Thumbnail": "/productImages/assets/img/icon18.gif"
},
"Barcode": {
"Barcode": "50622132430794"
},
"Currency": "£",
"Description": "Description goes here",
"Id": 44305,
"Packshots": [
"/productImages/238556/1min.jpg",
"/productImages/238556/2med.jpg",
"/productImages/238556/3max.jpg"
],
"Pegis": [],
"Platform": {
"Button": "Xbox 360",
"ID": 0
},
"Publisher": {
"Description": null
},
"Release": "/Date(1392940800000+0000)/",
"Screenshots": [
{
"ScreenshotMax": "/productImages/238556/5scrmax1.jpg",
"ScreenshotMin": "/productImages/238556/4scrmin1.jpg"
}
],
"Title": "Product title 2 goes here",
"Variants": [
{
"Id": 58242,
"MaxOrderQuantity": 3,
"Presellable": true,
"Price": 29.97,
"PriceCultureFormat": "29.97",
"PriceWithCurrencyFormat": "£29.97",
"Sku": 238556,
"Type": {
"Description": "New"
}
},
],
"Vendor": {
"Description": ""
},
},
"s238556": {
"Age": {
"Description": "Age 18+",
"Thumbnail": "/productImages/assets/img/pegi/icon18.gif"
},
"Barcode": {
"Barcode": "5060134530794"
},
"Currency": "£",
"Description": "Description here",
"Id": 654654,
"Packshots": [
"/productImages/238556/1min.jpg",
"/productImages/238556/2med.jpg",
"/productImages/238556/3max.jpg"
],
"Pegis": [],
"Platform": {
"Button": "PlayStation 3",
"ID": 0
},
"Publisher": {
"Description": null
},
"Release": "/Date(1392940800000+0000)/",
"Screenshots": [
{
"ScreenshotMax": "/productImages/238556/5scrmax1.jpg",
"ScreenshotMin": "/productImages/238556/4scrmin1.jpg"
},
{
"ScreenshotMax": "/productImages/238556/7scrmax2.jpg",
"ScreenshotMin": "/productImages/238556/6scrmin2.jpg"
},
],
"Title": "Product title 2 goes here",
"Variants": [
{
"Id": 58242,
"MaxOrderQuantity": 3,
"Presellable": true,
"Price": 29.97,
"PriceCultureFormat": "29.97",
"PriceWithCurrencyFormat": "£29.97",
"Sku": 238556,
"Type": {
"Description": "New"
}
},
],
"Vendor": {
"Description": ""
},
"VideoHTML": "html here",
"status": {
"Response": "product found",
"Success": true
}
}
}
</script>
The above example is the output I get for two products.
If I try to get access to this data this is where I have a problem
<script type="application/javascript">
function getSKU(s)
{
console.log(SKUinfo.s.Title);
}
getSKU(s238554);
</script>
I imagine this is being caused when I am passing the argument s back to the function getSKU a the node selection in the data object. In this I would expect the console output to be the Title from SKU s238554.
What I get however, is: Uncaught ReferenceError: s238554 is not defined
I would appreciate any guidance that can be offered as I am a javascript novice.
Access your property by used[] on SKUinfo.s.Title like SKUinfo[s].Title
And also pass your property name within the quotes 's238554' as it's not variable.
Something like this.
function getSKU(s){
console.log(SKUinfo[s].Title);
}
getSKU('s238554'); // s238554 within quotes.

Facebook Open Graph not returning all results for Books.Read?

When using the Facebook Open Graph explorer, I run the following, to get a list of my books read.
/706685881/books.reads?limit=25&offset=0
This returns only 5 results, even though I have more books read than that, and I've explicitly requested up to 25 results. Following the paging link to the (theoretical) more results, shows a page with no more results.
here's my output of the query:
{
"data": [
{
"data": {
"book": {
"id": "452418224806835",
"url": "https://www.facebook.com/pages/Fantastic-Voyage/452418224806835",
"type": "books.book",
"title": "Fantastic Voyage"
}
},
"id": "10151871872740882"
},
{
"data": {
"book": {
"id": "106151566083577",
"url": "https://www.facebook.com/pages/The-Andromeda-Strain/106151566083577",
"type": "books.book",
"title": "The Andromeda Strain"
}
},
"id": "10151870390740882"
},
{
"data": {
"progress": [
{
"timestamp": 1388668020,
"percent_complete": 0
},
{
"timestamp": 1392949225,
"percent_complete": 100
}
],
"book": {
"id": "10150233066083545",
"url": "http://www.goodreads.com/book/show/10664113-a-dance-with-dragons",
"type": "good_reads:book",
"title": "A Dance with Dragons (A Song of Ice and Fire, #5)"
}
},
"id": "10151867499170882"
},
{
"data": {
"progress": [
{
"timestamp": 1391350736,
"percent_complete": 0
},
{
"timestamp": 1392569208,
"percent_complete": 100
}
],
"book": {
"id": "1390736374489290",
"url": "http://www.goodreads.com/book/show/18405477-city-of-the-sun",
"type": "good_reads:book",
"title": "City of the Sun"
}
},
"id": "10151860185710882"
},
{
"data": {
"book": {
"id": "526531387368738",
"url": "http://apps.facebook.com/bookscout/?currworkid=9000000000133742",
"type": "books.book",
"title": "Gates of Fire"
}
},
"id": "10151226827780882"
}
],
"paging": {
"next": "https://graph.facebook.com/706685881/books.reads?fields=data&limit=25&offset=25&__after_id=10151226827780882"
}
}
Anybody seeing what I am doing wrong?

Categories

Resources