How to Use Select Value as Key for JSON in SQL - json

I have a tsql stored procedure that generates a json file of the database I am working with. A certain part of the json file is an array of properties with a name, value, and requirement variable. This part of the JSON file looks like this:
"Properties": [
{
"PropertyName": "Foo"
"PropertyValue": "Bar"
"Required": "True"
},
{
"PropertyName": "Foo2"
"PropertyValue": "Bar2"
"Required": "False"
}
]
This is generated as a subquery of a larger SQL query that creates the entire JSON document:
SELECT,...,
(SELECT P.Name as PropertyName, P.Value as PropertyValue, P.Requirement as Required
FROM Properties P FOR JSON PATH) as Properties
FROM Foo
FOR JSON PATH
I want the JSON file to be laid out so the value of PropertyName is the key for the other two values:
"Properties" [
{"Foo": {{"PropertyValue": "Bar"},{"Required": "True"}},
etc.
]
Ideally the code could be something like:
(Select P.Value as [[P.Name].PropertyValue], P.Requirement as [[P.Name].Required]
FROM Properties P
FOR JSON PATH)
But obviously that isn't a legal expression. Is there any way I can do this within an SQL framework or should I modify the file after it's created?

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.

How to traverse through all elements of json using robotframework and fetch only those that match the query

I am trying to extract a node from a json file for a json element that matches another node in same element.
To be more specific, I want the names of all students in the sample json below who has "certified":"false"
Example JSON
{
"Students": [
{
"name": "John",
"Rank": "1",
"certified":"false"
},
{
"name": "Ashley",
"Rank": "5",
"certified":"true"
}
]
}
Code i am using is (gives me empty output) :
Library JSONLibrary
JSON_Verification
[Documentation] Testing JSON load logic
${metadataJson_object}= Load JSON From File ../TestData/sample.json
Log ${metadataJson_object}
#{studentName}= Get Value From Json ${metadataJson_object} "$..[?(#.certified=='false')]#.name"
Log #{studentName}
Indeed you were very close to it, # notation is not needed after filter. Just change the json path to =
$.Students[?(#.certified=='false')].name
Here :
$ -> root element
. -> child operator or to access the property
?() -> filter expression and
# -> current node
${json}= Convert String to JSON ${Getjson}
${name}= Get Value From Json ${json} $.Students[?(#.certified=='false')].name
Output

Dynamically build json using groovy

I am trying to dynamically build some json based on data I retrieve from a database. Up until the opening '[' is the "root" I guess you could say. The next parts with name and value are dynamic and will be based on the number of results I get from the db. I query the db and then the idea was to iterate through the result adding to the json. Can I use jsonBuilder for the root section and then loop with jsonSlurper to add each additional section? Most of the examples I have seen deal with a root and then a one time "slurp" and then joining the two so wasn't sure if I should try a different method for looping and appending multiple sections.
Any tips would be greatly appreciated. Thanks.
{
"hostname": "$hostname",
"path": "$path",
"extPath": "$extPath",
"appName": "$appName",
"update": {"parameter": [
{
"name": "$name",
"value": "$value"
},
{
"name": "$name",
"value": "$value"
}
]}
}
EDIT: So what I ended up doing was just using StringBuilder to create the initial block and then append the subsequent sections. Maybe not the most graceful way to do it, but it works!
//Create the json string
StringBuilder json = new StringBuilder("""{
"hostname": "$hostname",
"path": "$path",
"extPath": "$extPath",
"appName": "$appName",
"update": {"parameter": ["""
)
//Append
sql.eachRow("""<query>""",
{ params ->
json.append("""{ "name": "params.name", "value": "params.value" },""");
}
)
//Add closing json tags
json.append("""]}}""")
If I got your explanation correctly and if the data is not very big (it can live in memory), I'd build a Map object (which is very easy to work with in groovy) and convert it to JSON afterwards. Something like this:
def data = [
hostname: hostname,
path: path,
extPath: extPath,
appName: appName,
update: [parameter: []]
]
sql.eachRow(sqlStr) { row ->
data.update.parameter << [name: row.name, value: row.value]
}
println JsonOutput.toJson(data)
If you're using Grails and Groovy you can utilize grails.converters.JSON.
First, define a JSON named config:
JSON.createNamedConfig('person') {
it.registerObjectMarshaller(Person) {
Person person ->
def output = [:]
output['name'] = person.name
output['address'] = person.address
output['age'] = person.age
output
}
}
This will result in a statically defined named configuration for the Object type of person. Now, you can simply call:
JSON.use('person') {
Person.findAll() as JSON
}
This will return every person in the database with their name, address and age all in one JSON request. I don't know if you're using grails as well in this situation though, for pure Groovy go with another answer here.

Entity reference for 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
}

Order of performing sorting on a big JSON object

i have a big json object with a list of "tickets". schema looks like below
{
"Artist": "Artist1",
"Tickets": [
{
"Id": 1,
"Attr2Array": [
{
"Att41": 1,
"Att42": "A",
"Att43": null
},
{
"Att41": 1,
"Att42": "A",
"Att43": null
},
],
.
.
.
(more properties)
"Price": "20",
"Description": "I m a ticket"
},
{
"Id": 4,
"Attr2Array": [
{
"Att41": 1,
"Att42": "A",
"Att43": null
},
{
"Att41": 1,
"Att42": "A",
"Att43": null
},
],
.
.
.
.
(more properties)
"Price": "30",
"Description": "I m a ticket"
}
]
}
each item in the list has around 25-30 properties (some simple types, and others complex array as nested objects)
i have to read the object from an api endpoint and extract only "ID" and "Description" but they need to be sorted by "Price" which is an int for example
In what order shall i proceed with this data manipulation
Shall i use the json object, deserialised it into another object with just those 2 properties (which i need) and THEN perform sort "asc" on the "Price"?
Please note that after i have the sorted list i will have to convert it back to a json list because the front end consumes a json after all.
What i dont like about this approach is the cycle of serialisation and deserialisation that happens
or
I perform a sort on the json object first (using for example a binary/bubble sort) and then use the object to create a strongly typed (deserialised) object with just those 2 properties and then serialise it back to pass to the front end
I dont know how performant the bubble sort will be and if at all i will get any gain in performance for large chunks of data processing.
I also need to keep in mind that this implementation can take into account other properties like "availabilitydate" because at a later date, this front end could add one more filter like "availabilitdate" asc
any help is much appreciated
thanks
You can deserialize your JSON string (or file) using the Microsoft System.Web.Extensions and JavaScriptSerializer.DeserializeObject.
First, you must have classes associated to your JSON. To create classes, select your JSON sample data and, in Visual Studio, go to Edit / Paste Special / Paste JSON As Classes.
Next, use this sample to deserialize a JSON string to typed objects, and to sort all Tickets by Price property using Linq.
String json = System.IO.File.ReadAllText(#"C:\Data.json");
var root = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Rootobject>(json);
var sortedTickets = root.Tickets.OrderBy(t => t.Price);