Entity reference for JSON - json

I was wondering, is there something similar to entity reference substitution for JSON ? Let say i have the following JSON file
{
"sql1": "select * from ?? where date = 20030405",
"sql2": "select * from ?? where date = 20030708",
"table":"tab1"
}
How can i substitute the value of the key "table", which is "tab1" at the appropriate place in the values for the keys "sql1" and "sql2" ?

If I understand you correctly, you can find more info here:
http://json-spec.readthedocs.org/en/latest/reference.html
and here is an example
A JSON Reference is a mapping with a unique key $ref, which value is a JSON Pointer. For example, this object:
{
"foo": {"$ref": "#/bar"},
"bar": true
}
Can be resolved as:
{
"foo": true,
"bar": true
}

Related

How to traverse JSON object using a key like method name { "GROUP(date)": "2019-09"} - ballerina

I have a json object like following
"values": {
"GROUP(date)": "2019-09",
"GROUP(account)": [
{
"value": "228",
"text": "Subscription"
}
],
"SUM(amount)": "630.638",
}
The json object consists of key value pairs like above snippet.
But the key is like method name coz there is a bracket like GROUP(date).
when I try to traverse using the key it not recognize the key.
values.GROUP(date)
what is the way to get the value using this kind of key in ballerina?
To use field access like values.GROUP(date), the parentheses can be escaped.
values.GROUP\(date\)
Alternatively, if the static type of values is a map (e.g., map<json> which represents JSON objects), member access can be used with a string literal.
values["GROUP(date)"]
This is the answer that I found.
"values": {
"GROUP(date)": "2019-09",
"GROUP(account)": [
{
"value": "228",
"text": "Subscription"
}
],
"SUM(amount)": "630.638",
}
// direct call by key
string date = values["GROUP(date)"].toString();
// access value inside the array
json[] account = <json[]> values["GROUP(account)"];
map<json> account_obj = <map<json>> account[0];
string account_value = check account_obj.text;
I tries to define a record and access the object. But wasn't able to have the approach.

JSON schema conditional check in JSON object within array

Here is the desired schema and json for illustration purpose. Please see the link below.
JSON Schema and JSON
{
"id": "123" ,
"ts": "1234567890",
"complex_rules":
[
{
"type":"admin",
"rule":{
"rights":"all",
"remarks": "some admin remarks"
}
},
{
"type":"guest",
"rights": "limited"
},
{
"type":"anonymous",
"rights": "blocked"
}
]
}
The 'complex_rules' is an array of json object:
With type either be a : "admin", "guest", "anonymous" and the 'type' attribute is MANDATORY.
Each object in array can have its own structure, but the type can be either of: "admin", "guest", "anonymous" only. No other type attribute is acceptable.
The conditions to evaluate:
The type of object in the array cannot re-occur in the array. (I know this seems to be not possible, so we can ignore this)
If attribute "rights" in the {type=admin object} with any value, then we cannot have "rights": "limited" or any value in {type=guest object}. The JSON Schema validation must complain about this.
Another twist, either object {type":"guest"}or {type":"anonymous"} can exist. Both types cannot coexist along with other types.
----Update
The above link is the solution this question.
In regards to 1 and 2:
You need to use a combination of if, then, and not keywords to construct the logic you require with the correct level of applicability.
In regards to 3:
The type of object in the array cannot re-occur in the array. (I know
this seems to be not possible, so we can ignore this)
Right, that's correct, it's not possible as of draft-7 JSON Schema.

when pass string variable to jasonparser jsonobject returns null

To read the json file I have created below method in groovy. I am calling it from another class.
class WUPage{
#Shared
String fileContents ;
def jsonSlurper ;
def jsonObject ;
public String getValueFromJsonFile(String fileName, String jsonKey){
fileContents = new File(fileName).getText('UTF-8')
jsonSlurper = new JsonSlurper()
jsonObject = jsonSlurper.parseText(fileContents)
println " Json Key from method is : " + jsonObject.jsonKey
println " Json Key hardecoded is : " + jsonObject.pipe.id
return jsonObject.jsonKey
}
}
When I am calling this method from another class I am passing file name and the key to it like below
getValueFromJsonFile(jsonFIleName, "pipe.id")
I am getting below output
Json Key from method is : null
Json Key hardecoded is : [India]
From above output second line is correct when key is hardcoded. It seems it's not recognizing key coming from method parameter.
Can you please help me on this.
Json File is :
{
"source": [
{
"id": "manish",
"type": "csv",
"path": "/home/surya/f1.txt",
"delimiter": ",",
"tableName": "table1",
"schema": "f1,f2,f3,f4,f5"
}
],
"pipe": [
{
"id": "India",
"sql": "select f1,f2,f5 from table1"
}
],
"sinks": [
{
"id": "output1",
"type": "aaa",
"path": "/home/surya/out",
"format": "json"
}
]
}
It is because the dot in the key name is not doing what you expected. You didn't show your JSON data in the original post, but I can deduce that there is a top-level object "pipe" that contains an id key. Groovy can't magically know this, so it applies the entire parameter as a top-level key, not as compound deep keys.
You are trying to always get the key jsonKey from that map.
def json = [a: [b: 42]] // just some map, but that's what your JsonSlurper result is
def key = 'a' // start with a simple key
println json.key // wont work, because groovy will access the key `key`
// => null
println json."$key" // works, now
// => [b:42]
key = 'a.b'
println json."$key" // wont work, because you can not access recursive keys like that
// => null
So at that point you have to decide, what to do and how comples your path there can become and what's the source of your path (e.g. is is always a string from somewhere else or is this for developer convenience).
You can Eval a string
You can "split" the path at . and then reduce this list over the map
Instead of a string pass in a Closure, that accesses the data

Using JPATH, how do I select a JSON value inside another JSON string?

I have the following JSON (simplified / minimized to show only pertinent parts) returned from a web service:
{
"results": [{
"paramName": "OutputPolyline",
"dataType": "String",
"value": "#{\"hasM\":true,\"paths\":[[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]}"
}],
"messages": []
}
I use the following code to parse the JSON and grab the value of the "value" key:
JObject obj = JObject.Parse(json);
JToken token = obj.SelectToken("$.results[?(#.paramName == 'OutputPolyline')]['value']");
Console.WriteLine(token.Path + " -> " + token);
The above code returns the entire value string as expected, like such "#{\"hasM\":true,\"paths\":[[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]}"
Building on the above code, how do I get only the value of the paths key? In this example, return only [[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]
You cannot extract the path values from the root object via a single JsonPath query since the value of the value property is just a string literal that happens itself to be re-serialized JSON. It needs to be extracted and recursively parsed as JSON after first trimming off the # character, and Json.NET has no built-in query operator to do that as of the current version, 9.0.1.
Thus you need to do something like:
JToken token = obj.SelectToken("$.results[?(#.paramName == 'OutputPolyline')]['value']");
var paths = JToken.Parse(token.ToString().Trim('#')).SelectToken("paths");
Sample fiddle.

JSON with duplicate key names losing information when parsed

So either I go back and tell someone that they should fix their JSON, or I need to find out what I am doing wrong. Here is the JSON, notice that parameter occurs three times:
String j= '''{
"jobname" : "test",
"parameters" : {
"parameter": {"name":"maxErrors", "value":"0"},
"parameter": {"name":"case", "value":"lower"},
"parameter": {"name":"mapTable", "value":"1"}
}
} '''
And I am trying to get each name & value. My code
def doc = new JsonSlurper().parseText(j)
def doc1 = doc.entrySet() as List
def doc2 = doc.parameters.entrySet() as List
println "doc1.size===>"+doc1.size()
println "doc1===>"+doc1
println "doc2.size===>"+doc2.size()
println "doc2===>"+doc2
And my results:
doc1.size===>2
doc1===>[jobname=test, parameters={parameter={name=mapTable, value=1}}]
doc2.size===>1
doc2===>[parameter={name=mapTable, value=1}]
How come I only get one parameter? Where are the other two? It looks like JSON only keeps one parameter and discards the other ones.
The JSON is not in the correct format. There should not be duplicate key in the same hierarchy or they will override each other.
It should have been an array of paramters.
Like this,
String j= '''{
"jobname" : "test",
"parameters" : [
{"name":"maxErrors", "value":"0"},
{"name":"case", "value":"lower"},
{"name":"mapTable", "value":"1"}
]
}