JSONata transformation script for taking source as it is with some override/modifications - jsonata

I have JSON, for example:
{
"PDMSReferenceNumber": "11340",
"OntologyClass": "rdl:P101003917",
"TopTag": "DEEP1",
"ServiceDescription2": "Main manual",
"SystemVoltagePrimaryWinding": "",
"ClearOpeningHeight": "true"
}
Is it possible to create JSONata script like this:
{
"*": *,
"MainTag": TopTag
}
The result should be
{
"PDMSReferenceNumber": "11340",
"OntologyClass": "rdl:P101003917",
"ServiceDescription2": "Main manual",
"SystemVoltagePrimaryWinding": "",
"ClearOpeningHeight": "true",
"MainTag": "DEEP1"
}
So I want to take the source JSON is it is and make some override and modifications.
Thank you!

You could try using the Transform Function - https://docs.jsonata.org/other-operators#-------transform
So this basic "copys" TopTag to MainTag, and adds to object and then deletes TopTag
$ ~> |$|{'MainTag': TopTag}, ['TopTag']|
Here you go to show it:
https://try.jsonata.org/YqpO6oUk9

Exactly what JSONata does for you "transform" JSON.
You can simply do this:
$.{
"MainTag": TopTag,
"PDMSReferenceNumber": PDMSReferenceNumber,
"OntologyClass": OntologyClass,
"ServiceDescription2": ServiceDescription2,
"SystemVoltagePrimaryWinding": SystemVoltagePrimaryWinding,
"ClearOpeningHeight": ClearOpeningHeight
}
So the left part is the "key" for your new object, and the right is the "Key" from your source JSON (hence we have "MainTag": TopTag)

Related

Sort GraphQL query results in the exact order of input array

I need to get a number of items from a GraphQL enabled database (no control over its schema) and output them in the exact order called.
For example, if the database holds the items 1,2,3 in that respective order I need to get them as 3,1,2.
Query:
{items(filter: {id: {_in: ["3","1","2"] } } ) {data}}
Actual result:
{"data": {"items": [{"data": "data-from-1"},{"data": "data-from-2"},{"data": "data-from-3"}]}}
Expected result:
{"data": {"items": [{"data": "data-from-3"},{"data": "data-from-1"},{"data": "data-from-1"}]}}
So I guess that what I'm looking for is a 'meta' operator that relates to other operators rather than the actual query – something like:
sort:["_in"] or orderby:{operator:"_in"}
...but I didn't manage to find out if such a thing exists or not.
So is it possible in general or maybe in some flavour of GraphQL? Or is it my only choice to prebuild a query with aliases and do it like this:
{
_3: items(filter:{id: { _eq: "3" }}){data}
_1: items(filter:{id: { _eq: "1" }}){data}
_2: items(filter:{id: { _eq: "2" }}){data}
}
Which GraphQL client are you using?
If you're using Apollo, and you really don't have access to the schema/resolvers in the server, you can create a local field and resolve it on your own, and so you can manipulate as much as you want.
Reference
https://www.apollographql.com/docs/react/local-state/managing-state-with-field-policies/#defining
Basically, if you're querying a field like:
query {
someQuery(someFilter: {foo: "bar"}) {
items {
data
}
}
}
You can create a local field and write a typePolicy to it. Then you can query something like:
query {
someQuery(someFilter: {foo: "bar"}) {
items {
data
}
parsedItems #client
}
}
Then you can get data from ìtems and resolve parsedItems locally as you want.

JSONata: How to substitute . with _ in key names?

Update: editing question to provide a multi-level object example:
{
"An.Example": "Dots.are.okay.in.values",
"Product": {
"Product.ID.Number": 858383 ,
"Product.Name": "Bowler Hat",
"Unit.Cost": 12
}
}
Exerciser: https://try.jsonata.org/ZdaDTJFMA
[original question]
Hello JSONata newbie checking in again. Given this source which I'm keeping very simple for the purposes of this example...
{
"Product.Name": "Bowler Hat",
"Product.ID.Number": 858383
}
How can I transform any "." in key names to "_"? The key names will not be known in advance so I can't simply hard code. Desired result:
{
"Product_Name": "Bowler Hat",
"Product_ID_Number": 858383
}
I took a look at the example shown here -- https://try.jsonata.org/ry9G5Xr3H -- which was in response to this question -- Find fields which contains a text and replace it with another text -- but cannot come up w/ the proper adjustments to address my need.
Sample JSON and non-working code here -- https://try.jsonata.org/uOwYJOLto
Thank you in advance for any assistance or suggestions.
$each(function($v, $k) {
{ $replace($k, '.', '_'): $v}
}) ~> $merge()
See https://try.jsonata.org/uZgm69Bfy
If you want to traverse a hierarchy of objects, then you'll need write a recursive function:
(
$dotsToUnderscores := $each(?, function($v, $k) {
{ $replace($k, '.', '_'): $type($v) = 'object' ? $dotsToUnderscores($v) : $v}
}) ~> $merge;
$dotsToUnderscores($)
)
See https://try.jsonata.org/WsfsFGhjE or https://try.jsonata.org/r2GrHYYou

How to Extract Json value from an array based on some value in sub array

I want to get the "id":1922 from the main array based on the "id":1 from the sub array 'media_type':
{
"data":[
{
"id":1922,
"media_count":1,
"title":"test",
"description":"Test",
"address":null,
"latitude":null,
"longitude":null,
"privacy":1,
"license":1,
"is_comment_disable":0,
"is_adult":0,
"media_type":{
"id":1,
"slug":"photo",
"title":"Photo"
}
}
]
}
Instead of converting json to object, you can use json parser
For reference: https://www.programcreek.com/java-api-examples/index.php?api=javax.json.stream.JsonParser
Try with JSON path to get value base on media_type
$..data[?(#.media_type>0)].id

Flutter internationalization - Dynamic strings

I'm translating my app to spanish using the intl package.
locales.dart
class AppLocale {
...
String get folder => Intl.message("Folder", name: 'folder');
...
}
messages_es.dart
class MessageLookup extends MessageLookupByLibrary {
get localeName => 'es';
final messages = _notInlinedMessages(_notInlinedMessages);
static _notInlinedMessages(_) => <String, Function> {
"folder": MessageLookupByLibrary.simpleMessage("Carpeta"),
};
}
I call it using the following code:
AppLocale.of(context).folder
It is working fine.
However, I need to create "dynamic" strings. For example:
"Hi, {$name}"
Then I would call this string, passing this "name" as parameter, or something like this. It would be translate as "Hola, {$name}" in spanish.
It is possible using this intl package?
If you follow the official internationalization docs and specify all your phrases in .arb files, you can do parameters like this:
{
"greeting": "Hi, {name}!",
"#greeting": {
"description": "Greet the user by their name.",
"placeholders": {
"name": {
"type": "String",
"example": "Jane"
}
}
}
}
When you compile your code, a function like the following will be generated for you, complete with a nice docbloc to power your IDE tooltips:
/// Greet the user by their name.
///
/// In en, this message translates to:
/// **'Hi, {name}!'**
String greeting(String name);
So you can just use it like this:
Text(AppLocalizations.of(context)!.greeting("Koos"))
The README of the intl package explains that example
https://github.com/dart-lang/intl
The purpose of wrapping the message in a function is to allow it to
have parameters which can be used in the result. The message string is
allowed to use a restricted form of Dart string interpolation, where
only the function's parameters can be used, and only in simple
expressions. Local variables cannot be used, and neither can
expressions with curly braces. Only the message string can have
interpolation. The name, desc, args, and examples must be literals and
not contain interpolations. Only the args parameter can refer to
variables, and it should list exactly the function parameters. If you
are passing numbers or dates and you want them formatted, you must do
the formatting outside the function and pass the formatted string into
the message.
greetingMessage(name) => Intl.message(
"Hello $name!",
name: "greetingMessage",
args: [name],
desc: "Greet the user as they first open the application",
examples: const {'name': "Emily"});
print(greetingMessage('Dan'));
Below this section there are more complex examples explained that also deal with plurals and genders.
In order to use placeholders in your translations you need to:
Add that placeholder as a getter argument
Mention that placeholder with $ prefix in the translation (ie $name)
Add the placeholder in args list when calling Intl.message
So a full example looks like this:
greetingMessage(name) => Intl.message(
"Hello $name!",
name: 'greetingMessage',
args: [name]
);
Follow this link. Once you have finished all steps, do the below changes in your .arb file:
{
"title": "App Title",
"helloWorld": "{name1} and {name2} must be different",
"#helloWorld": {
"description": "The conventional newborn programmer greeting",
"placeholders": {
"name1": {
"type": "String"
},
"name2": {
"type": "String"
}
}
},
"appInfo": "Information about your app",
}

Create or append to an array in a rethinkdb document

How should we append an item to an array if the array exists, or create an array and insert to it.
I tried the merge command but that doesn't allow merging arrays, only replacing them.
r.db('testdb').table('users').get('27e55a4a-a6f8-4ec9-bd02-f55f206700ff').merge({ 'hobbies':['Reading'] })
I further tried passing a function but doesnt seem to work:
r.db('testdb').table('users').get('27e55a4a-a6f8-4ec9-bd02-f55f206700ff').merge(function(user) {
return r.branch(user('hobbies').eq(null),
{ 'hobbies' : ['Reading'] }
user('hobbies').append('Reading'))
});
Consider the below doc structure:
{
"email": email.123#gmail.com, »
"id": "27e55a4a-a6f8-4ec9-bd02-f55f206700ff" ,
"image": https://lh4.googleusercontent.com/-O4ZXcLRpkHE/AAArAAAAAAAI/AdAAAAAAALMM/Fq968TTkd88Y/photo.jpg?sz=50, »
"name": "John Doe"
}
If I would like to add hobbies as an array how should I do it. The query has to work both if the hobby array exists or not.
The most idiomatic way would be .update(function(user) { return {hobbies: user('hobbies').default([]).append('reading')}; })
Finally I have figured out myself.
r.db('testdb').table('users')
.get("27e55a4a-a6f8-4ec9-bd02-f55f206700ff")
.update(function(user){
return r.branch(user.hasFields('hobbies'),
{ hobbies: user('hobbies').append('reading')},
{ hobbies : ['reading']}
)})

Resources