I have a problem with rawToChar() and write_json() where my result is a .json file that includes \n and \ and cannot be viewed in a "pretty" manner using notebook+. In addition I can't unfold or Uncollapse the result.
My working sequence is:
request <- httr::GET(
url = "https://myurl",
httr::content_type("application/json")
)
existing_distribution.json = jsonlite::prettify(rawToChar(request$content))
write_json(existing_distribution.json, "distribution.json"), pretty = TRUE)
When I open distribution.json with notepad+ I get a single line ...
["{\n \"ConfigurationStatus\": \"NOT_DEFINED\",\n \"economicStatus ... blahblah \n}\n"]
Any ideas?
Let there be a file example.json mocking your API containing
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
This is how to read the file as a raw sequence of bytes, parses it and saves it as prettified json:
library(jsonlite)
library(readr)
read_file_raw("example.json") %>%
rawToChar() %>%
parse_json() %>%
write_json("out.json", pretty = TRUE)
Resulting in file out.json containing:
{
"glossary": {
"title": ["example glossary"],
"GlossDiv": {
"title": ["S"],
"GlossList": {
"GlossEntry": {
"ID": ["SGML"],
"SortAs": ["SGML"],
"GlossTerm": ["Standard Generalized Markup Language"],
"Acronym": ["SGML"],
"Abbrev": ["ISO 8879:1986"],
"GlossDef": {
"para": ["A meta-markup language, used to create markup languages such as DocBook."],
"GlossSeeAlso": [
["GML"],
["XML"]
]
},
"GlossSee": ["markup"]
}
}
}
}
}
Related
I've got this very simple json :
{
"authors": [
{
"id": 1,
"name": "Douglas Adams"
},
{
"id": 2,
"name": "John Doe"
}
],
"books": [
{
"name": "The Hitchhiker's Guide to the Galaxy",
"author_id": 1
}
]
}
I would like to request the name of the author of "The Hitchhiker's Guide to the Galaxy".
I've tried this JSON path but it doesn't work:
$.authors[?(#.id == $.books[?(#.name == "The Hitchhiker's Guide to the Galaxy")].author_id)].name
All online tools I tried indicate a syntax error which seems due to the presence of a JSON path inside my filter.
Could anyone please help me figure out what's wrong and what is the right syntax?
Thanks!
When you running this filter
$.books[?(#.name == "The Hitchhiker's Guide to the Galaxy")].author_id
it returns an array instead of a value:
[
1
]
Syntax error occurs when you pass an array to compare with the value of id:
$.authors[?(#.id == {the array value}].author_id)].name
However, you may not be able to extract the value using JSONPath, depends on the language you are using. See Getting a single value from a JSON object using JSONPath
I am using R and have one question on how to pass parameter to the REST API REQUEST.
I already got the token and I am using R, and need to retrieve data from REST API service, by passing some parameters. Here is my code:
library(httr)
r <- POST("https://XXXXXXXX/api/locationhazardInfo",
add_headers("Content-Type"="text/plain; charset=UTF-8",
Accept="text/plain",
"Authorization"=paste("Bearer", tok)),
body = list(
"Latitude":40.738269,
"Longitude":-74.02826,
"CountryCode":"USA",
"HazardLayers":[
{
"LayerId":"18",
"Description":""
},
{
"LayerId":"6",
"Description":""
}
],
"Distances":[
{
"Value":1,
"Unit":"miles"
}
]
)
)
The tok is the token I got from previous step. And I got the systax errors (seem all syntax errors) as shown below,
Any input is greatly appreciated.
here is the screenshot of the error
Your body isn't a list. (I don't think!). I also think you have a rogue ) at the end (second last) which should be a }
A list would look like:
body = list(x = "A simple text string", y="Another String")
Your body is JSON encoded text.
body = '{"a":1,"b":{}}', encode = "raw")
So your code might look like this:
library(httr)
r <- POST(
"https://XXXXXXXX/api/locationhazardInfo",
add_headers(
"Content-Type"="text/plain; charset=UTF-8",
Accept="text/plain",
"Authorization"=paste("Bearer", tok)
),
body = '{
"Latitude":40.738269,
"Longitude":-74.02826,
"CountryCode":"USA",
"HazardLayers":[
{
"LayerId":"18",
"Description":""
},
{
"LayerId":"6",
"Description":""
}
],
"Distances":[
{
"Value":1,
"Unit":"miles"
}
]
}',
encode = "raw" )
An update, here is the solution at least it fixed my problem:
rg <- POST(url,
# add_headers("Content-Type"="text/plain; charset=UTF-8",
add_headers("Content-Type"="application/json",
Accept="text/plain",
"Authorization"=paste("Bearer", tok)),
body = '{
"Latitude":40.738269,
"Longitude":-74.02826,
"CountryCode":"USA",
"HazardLayers":[
{
"LayerId":"18",
"Description":""
},
{
"LayerId":"6",
"Description":""
}
],
"Distances":[
{
"Value":1,
"Unit":"miles"
}
]
}' ,
encode = "raw" #### , verbose()
)
I have some JSON which I have no control over it's from a third-party supplier and the quotes are not handled properly resulting in malformed JSON. I have asked them to correct it but in the meantime, I would like to be able to use it.
var json = "{
"news": {
"headline": "Headline",
"items: [
{
"title": "title1",
"description": "description1",
},
{
"title": "title2",
"description": "description2",
},
{
"title": "title3",
"description": "description "with quotes" in the middle",
},
]
}
}";
I am trying to use DeserializeObject with it
var obj = JsonConvert.DeserializeObject<MyClass>(json);
Ideally, I would like all three items in my deserialised object, but even two would be better than the DeserializeObject just blowing up because the JSON is badly formatted.
Is there a possible correction which can be applied? I have looked at regexes but it's difficult to come up with something that could work with long and complex examples with many more items than this simplified version.
I would like to add to add a custom extension to my Schedule resource.
In my app, Schedule have visit motives (reasons). I know there's a list of classified appointments / encounter reasons but I would like to use mine.
I have something like this :
{
"resourceType":"Schedule",
"identifier":"logical_id",
"type":"schedule_speciality",
"actor":{
"practioner_id":"identifier",
"practioner_name":"practioner name"
},
"external_id":{
"extension":[
{
"url":"http://api.test.com/fhir/schedule/external_id",
"valueIdentifier":"external_id"
}
]
},
"visit_motives":{
"extension":[
{
"url":"https://api.test.com/fhir/ValueSet/schedule#visit_motives",
"valueString":"vist_motive1"
},
{
"url":"https://api.test.com/fhir/ValueSet/schedule#visit_motives",
"valueString":"vist_motive2"
},
{
"url":"https://api.test.com/fhir/ValueSet/schedule#visit_motives",
"valueString":"vist_motive3"
}
]
},
"practice_id":{
"extension":[
{
"url":"https://api.test.com/fhir/schedule/practice_id",
"valueIdentifier":"practice_id"
}
]
}
}
I'm not sure about this part :
"visit_motives":{
"extension":[
{
"url":"https://api.test.com/fhir/ValueSet/schedule#visit_motives",
"valueString":"vist_motive1"
},
{
"url":"https://api.test.com/fhir/ValueSet/schedule#visit_motives",
"valueString":"vist_motive2"
},
{
"url":"https://api.test.com/fhir/ValueSet/schedule#visit_motives",
"valueString":"vist_motive3"
}
]
}
Is it correct to add an extension this way ? There are always multiple visit motives for a specific schedule so I have to list them.
I also have seen this kind of things :
"visit_motives": {
"coding": [
{
"system": "https://api.test.com/fhir/ValueSet/schedule#visit_motives",
"code": "visit_motive1"
}
]
}
Which one is the correct one or am I wrong ?
There are several issues here:
It seems odd to capture a "reason" on a schedule. A schedule says when a particular clinician or clinic or other resource is available. E.g. "Dr. Smith takes appointments Mon/Wed/Fri from 1pm-4pm". So if you were to capture a reason on the resource, it would reflect "Why does Dr. Smith have a schedule?" Typically reasons are captured for an individual Appointment. That's the resource that reserves a particular slot for a planned visit. And Appointment already has an element for reason where you're free to use your own codes or just send text.
You have extensions to convey identifiers, but Schedule already has an element for identifiers. Why would you use extensions instead of the standard element? Note that you can use the "system" and/or "type" components to differentiate different kinds of identifiers.
You're sending "identifier", "type", "name", etc. as simple strings - but they're complex data types, so you need to communicate the child elements
actor is of type Reference - that means you need to point to the Practitioner resource. You can't send the properties in-line. (If the Practitioner only exists in the context of the Schedule, you could use the "contained" approach which would use an internal reference, but containment doesn't seem to make sense in this use-case.
The URL for your extension contains ValueSet, which isn't correct - extensions are all structure definitions. Also, there shouldn't be a # symbol in the URL.
Your syntax for extensions is incorrect. You can't introduce new properties in FHIR. The property name for all extensions is just "extension". You differentiate by the URL. So your syntax should be:
{
"resourceType":"Schedule",
"id":"logical_id",
"extension": [
{
"url":"https://api.test.com/fhir/StructureDefinition/schedule-visit_motive",
"valueString":"vist_motive1"
},
{
"url":"https://api.test.com/fhir/StructureDefinition/schedule-visit_motive",
"valueString":"vist_motive2"
},
{
"url":"https://api.test.com/fhir/StructureDefinition/schedule-visit_motives",
"valueString":"vist_motive3"
}
],
"identifier": [
{
"system": http://api.test.com/fhir/NamingSystem/external_id",
"value": "external_id"
}
{
"system": http://api.test.com/fhir/NamingSystem/practice_id",
"value": "practice_id"
}
]
"type": {
"coding": {
"system": "http://somewhere.org/fhir/CodeSystem/specialties",
"code": "schedule_speciality"
},
"text": "Some text description of specialty"
},
"actor":{
"reference": "http://myserver.org/fhir/Practitioner/12345"
"display": "Dr. smith"
}
}
The following is my structure of data
[
{
"id": 1,
"title": "Welcome to my playground",
"description": "This is so fun to play with, you will like it <3",
"comments": [
{
"id": 1140406,
"comment": "this is an example comment",
"postId": 1
}
]
},
...
]
And I'm trying to use immutable js to do this operation
Get all the posts
Search for a post I want to add comment to
Adding the comments when the post is found
The following is my code
posts = posts.map((post) => {
if(post.get('id') == payload.post_id) {
return post.update('comments', (comments) => {
return comments.push(Map({
id: payload.id,
comment: payload.comment
}));
});
}
return post;
});
But I assume this pattern is very common and there should be a simpler way to do this in immutableJS. Any advice will be helpful, thanks.
First off, it's worth mentioning that your Data structure is Immutable Lists and Maps.. not JS Arrays and Objects.
OK, without changing your data structure you could do:
posts.map(post => post.get('id') === payload.post_id ?
post.update('comments', comments.push(payload) :
post)
If you were to change your data structure, and instead of having a List of posts, had a Map of post's with their ID as the key you could just do:
post.updateIn([payload.post_id, 'comments'], comments => comments.push(payload))
BTW you can use push or concat here, both will function the same.
Also, if comments may be undefined, you can provide a "noSetValue" as a List (https://facebook.github.io/immutable-js/docs/#/List/updateIn):
posts.map(post => post.get('id') === payload.post_id ?
post.update('comments', Immutable.List([]), comments.push(payload) :
post)
post.updateIn([payload.post_id, 'comments'], Immutable.List([]), comments => comments.push(payload))
For others who has the same question: One should consider a data normalisation (search for normalizr). You could then normalise your data to something like:
"entities": {
"posts": {
"1": {
"id": 1,
"title": "Welcome to my playground",
"description": "This is so fun to play with, you will like it <3",
"comments": [1140406, 1140407, 1140408]
},
"42" : {...}
}
"comments": {
"1140406": {
"id": 1140406,
"comment": "this is an example comment",
"postId": 1
},
"1140407": {...}
}
}
then updating post and comments becomes much easier