Freebase: working with "namespace-prefix key" Json Object - json

I have made a request to freebase API, and the query is:
{
"id" : "/m/01f8mn",
"key" : [{
"namespace" : "/wikipedia/en_id",
"value" : null
}],
"key" : [{
"namespace" : "/authority/mobygames/game",
"value" : null
}]
}​
And I got the answer from Freebase:
{
"code": "/api/status/ok",
"result": {
"id": "/m/01f8mn",
"key": [{
"namespace": "/wikipedia/en_id",
"value": "213502"
}],
"ns0:key": [{
"namespace": "/authority/mobygames/game",
"value": "prince-of-persia"
}],
"ns1:key": [{
"namespace": "/authority/giantbomb/game",
"value": "61-2561"
}]
},
"status": "200 OK",
"transaction_id": "cache;cache03.p01.sjc1:8101;2012-05-20T18:37:04Z;0060"
}
As you can notice, there is a "namespace prefix" key in the result ("ns0:key", "ns1:key")
The question is: how can I handle this with Javascript Object? Can anyone help?

When accessing properties with special characters in the name, access it as you would an associative array property:
yourObject.result["ns0:key"]
Since the namespace and value properties are stored inside of an object that is the first index of an array, to access the namespace and value, use the following syntax:
yourObject.result["ns0:key"][0].namespace
yourObject.result["ns0:key"][0].value // contains "prince-of-persia"
yourObject.result["ns1:key"][0].namespace
yourObject.result["ns1:key"][0].value // contains "61-2561"

Your initial query isn't valid JSON (the two "key" keys will overwrite each other), so I suspect there's an intermediary software layer involved (perhaps Freebase's query editor?).
If it would help to be able to control the prefixes (they're not really namespaces), you can make them up yourself to suit you. Use "key" and "other:key" or whatever scheme works for you. You could also re-write the query using the |= operator so you can specify both namespaces in a single key clause (e.g. "key":[{"namespace|=" :[ns1,ns2]}]).

for ( key in freebaseResult.result ) {
var i, resultArray = freebaseResult.result[key];
for ( i = 0; i < resultArray.length; i++ ) {
alert( resultArray[i].namespace + ": " + resultArray[i].value );
}
}

Related

How to update a specific JSON element inside a complex JSON document in postgresql 10

I have JSON document which is stored under single column of type jsonb inside postgresql which looks like below:
{
"resourceType": "Bundle",
"type": "transaction",
"entry": [
{
"fullUrl": "urn:uuid:100",
"resource": {
"resourceType": "Encounter",
"id": "110",
"status": "planned",
"priority": {
"coding": [
{
"code": "ASAP"
}
]
},
"subject": {
"reference": "Patient/123"
},
"appointment": [
{
"reference": "Appointment/12213#42"
}
],
"diagnosis": [
{
"condition": {
"reference": "Condition/condReferenceValue"
},
"use": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/diagnosis-role",
"code": "AD"
},
{
"system": "http://terminology.hl7.org/CodeSystem/diagnosis-role",
"code": "DD"
}
]
}
}
],
"hospitalization": {
"preAdmissionIdentifier": {
"system": "https://system.html"
}
},
"location": [
{
"location": {
"display": "Mumbai"
},
"status": "active"
},
{
"status": "planned"
}
]
},
"request": {
"method": "POST",
"url": "Encounter"
}
}
]
}
Now, I want to update value for reference under subject attribute. So, I tried below way but it throws an error:
update fhir.testing set names = jsonb_set(names,'{"subject":{"reference"','"Patient/1"',true) where id = 10;
Error:
SQL Error [22P02]: ERROR: malformed array literal: "{"subject":{"reference""
Detail: Unexpected array element.
I referred this link but didn't work out for me. How can I do it?
I don't use Postgres that much but from what i read in the relative jsonb_set example in the documentation of JSON functions (and since you want to update) shouldn't it be
jsonb_set(names, '{entry,0,subject,reference}','Patient/1', false)
instead of
jsonb_set(names,'{"subject":{"reference"','"Patient/1"',true)
jsonb
jsonb_set(target jsonb, path text[], new_value jsonb [, create_missing
boolean])
Returns target with the section designated by path replaced by
new_value, or with new_value added if create_missing is true (default
is true) and the item designated by path does not exist. As with the
path oriented operators, negative integers that appear in path count
from the end of JSON arrays.
EDIT
To explain the path used in jsonb_set, check this example.
jsonb_set('[{"f1":1,"f2":null},2,null,3]', '{0,f1}','[2,3,4]', false)
returns
[{"f1":[2,3,4],"f2":null},2,null,3]
As i understand if a sub-element in a complex JSON document is an array, you need to specify it's index e.g. 0,1,2,...
EDIT
Always look very carefully the structure of the JSON document. I simply write this because i did not see that subject was a child of resource and that is causing you the error.
So the correct path is actually '{entry,0,resource,subject,reference}'
Correct Query for your requirement is:
update fhir.testing
set names= jsonb_set(names, '{entry,0,resource,subject,reference}', '"Patient/1"' , false)
where id = 10;
Explanation
json_set takes 4 parameter
target_json (jsonb) - which accept jsonb type data. In your case it is names field.
path (text[]) - which accepts a text array. in your case it is '{entry,0,resource,subject,reference}'.
new_value (jsonb) - in your case you want to change it to '"Patient/1"'.
create_missing (boolean) - in your case it should be false. as you want to replace the existing one. if you want to create the reference with given value in case of not found then just mark it true.
the value is not valid json, try this out:
update fhir.testing set names = jsonb_set(names, '{"entry": [{"resource": {"subject":{"reference":"Patient/1"} }}]}',true) where id = 10;
You have to create a valid json, closing every { and every ], yours was
'{"subject":{"reference"'

How to remove one property from json input message using replace() expression in azure logic app?

{
"metadata": {
"id": "2",
"uri": "3",
"type": "2"
},
"Number": "2323600002913",
"Date": "04/21/2009",
"postingDate": "00/00/0000",
"ata": {
"results": [
{
"metadata": {
"id": "r",
"uri": "e2",
"type": "s2"
},
"item": "000010",
"data":"ad"
}
]
}
}
want to remove metadata property from above json message and output should be like below
{
"Number": "2323600002913",
"Date": "04/21/2009",
"postingDate": "00/00/0000",
"ata": {
"results": [
{
"item": "000010",
"data":"ad"
}
]
}
}
I tried with removeProperty() which is working for root level metadata but inside metadata not removed.
how to use replace() in this case or anything else to only remove metadata.
The simplest way is use inline code, cause even with removeProperty() expression to remove the metadata under results, it will return the results array data not the whole json data. Then you will have to combine them, it's not a convenient way.
And with inline code you could refer to my below picture. The variable json is the value from triggerbody, then just delete the node or key and return the json variable. And with this way, even you want to delete many metadata in the array, you could add a for loop to delete it, just think of it as plain js code.
Update:if you want to get value from variable,cause no support expression to get value from variable so use the below expression.
var json =wworkflowContext.actions.Initialize_variable.inputs.variables[0].value;
And about how to loop the array in the json refer to my below pic.

Are identical paths with the only difference that one uses query but the other path parameters allowed?

My problem is similar to the one asked in the "Paths that differ only in query parameter names" post. However, I am not interested in identical paths that use different query parameter; instead, my problem is concerning similar paths that use the same parameters but take those parameters as input in a different way, one as query parameters and the other as path parameters.
I tried using creating two different paths in my swagger.json file, one containing them as query parameters and the other as path parameters, but it did not work. Please see below my code:
'''swagger.json
{
// swagger initialisation
"paths":{
"foo_b_ar/{foo}/{bar}":{
"get":{
"summary":"foo foo"
"operationId": "super secret id"
"produces":[
"someName/json"
],
"parameters":[
{
"name" = "foo",
"in" = "path",
"description" = "something",
"required" = true,
"type" = "string"
},
{
"name" = "bar",
"in" = "path",
"description" = "something2",
"required" = true,
"type" = "string"
}
],
"responses":{
// something not relevant
} } },
"foo_b_ar":{
"get":{
"summary":"foo foo"
"operationId": "super secret id"
"produces":[
"someName/json"
],
"parameters":[
{
"name" = "foo",
"in" = "query",
"description" = "something",
"required" = true,
"type" = "string"
},
{
"name" = "bar",
"in" = "query",
"description" = "something2",
"required" = true,
"type" = "string"
}
],
"responses":{
// something not relevant
} } }
}
My question is whether what I am trying to do in the swagger.json file is allowed?
/foo_b_ar and /foo_b_ar/{foo}/{bar} (note the leading / - it's required in path names) are different paths.
/foo_b_ar/smth/other and /foo_b_ar/{foo}/{bar} are also different paths, the former (concrete) definition is supposed to match first if used.
Example of identical paths:
/{foo} and /{bar}
/foo_b_ar/{foo} and /foo_b_ar/{bar}
/foo_b_ar/{foo}/{bar} and /foo_b_ar/{param1}/{param2}
/foo_b_ar/{foo}/something and /foo_b_ar/{bar}/something
/foo_b_ar/something/{foo} and /foo_b_ar/something/{bar}
That is, identical paths are paths that would be the same if you removed the {parameters} from them.
As for why "it did not work", without knowing the details of what exactly did not work and where, it could be because your swagger.json is not valid JSON and also not a valid OpenAPI definition. Please validate it using a JSON validator (e.g. https://jsonlint.com) and in Swagger Editor (https://editor.swagger.io). Some of the errors are:
Missing commas between object fields in JSON.
Invalid key/value separators (= instead of :).
Missing / at the beginning of paths. "foo_b_ar" is not a valid path, it must be "/foo_b_ar".
Duplicate operation IDs: "operationId": "super secret id".

Replacing the value of JSON based on key value pair with jq

I have a JSON with the following structure
{
"name": "name",
"id": [
"abcdef"
],
"input_dataobjects": [
{
"id": "someid1",
"name": "somename1",
"provider": "someprovider",
"datatype": "somedatatype1"
},
{
"name": "some_name2",
"datatype": "some_datatype2",
"id": "some_id2"
}
]
}
What I am trying to achieve
in input_dataobjects if datatype == somedatatype1 then name = sonemewname1.
I can use the index of the input_dataobjects since my json always has the same structure. But is there any different way to achieve it by parsing through the input_dataobjects and find the index to replace? I am using jq to do JSON operations.
I tried with using the index like .input_dataobjects[0].name="someting" because i know the position of the datatype always.
The simplest and perhaps most efficient solution to the problem as stated is:
.input_dataobjects |=
map( if .datatype == "somedatatype1"
then .name = "sonemewname1"
else . end )

json schema for a map of similar objects

I wish to write a json schema to cover this (simplified) example
{
"errorMessage": "",
"nbRunningQueries": 0,
"isError": False,
"result": {
"foo": {"price":10.0, "country":"UK"},
"bar": {"price":100.2, "country":"UK"}
}
}
which can have this pretty trivial root schema
schema = {
"type":"object",
"required":True,
"properties":{
"errorMessage": {"type":"string", "required":True},
"isError": {"type":"boolean", "required":True},
"nbRunningQueries": {"type":"number", "required":True},
"result": {"type":"object","required":True}
}
}
The complication is the results {} element. Unlike a standard pattern where results would be an array of same objects - each with an id field or similar this response models a python dictionary which looks like this:
{
"foo": {},
"bar": {},
...
}
So given that a will be getting a results object of flexible size with no set keys how can I write json schema for this?
I don't control the input sadly or I'd rewrite it to be something like
{
"errorMessage": "",
"nbRunningQueries": 0,
"isError": False,
"result": [
{"id": "foo", "price":10.0, "country": "UK"},
{"id": "bar", "price":100.2, "country":"UK"}
]
}
Any help or links to pertinent examples would be great. Thanks.
With json-schema draft 4, you can use additionalProperties keyword to specify the schema of any new properties that you could receive in your results object.
"result" : {
"type" : "object"
"additionalProperties" : {
"type" : "number"
}
}
If you can restrict the allowed key names, then you may use "patternProperties" keyword and a regular expression to limit the permited key names.
Note that in json-schema draft 4 "required" must be an array which is bounded to the object, not to each property.