Generate child array json from given hierarchy levels object list - json

"questionnaireData": [
{
"questionaireType": "Q_AUTO_APPLICATION",
"cardID": "<blank>",
"setID": "<blank>",
"setName": "<blank>",
"sectionID": "<blank>",
"sectionName": "<blank>",
"pageID": "Person",
"fieldName": "LASTNAME",
"content": "Steve",
"fieldCode": "1111"
},
{
"questionaireType": "Q_AUTO_APPLICATION1",
"cardID": "Card 1",
"setID": "<blank>",
"setName": "<blank>",
"sectionID": "<blank>",
"sectionName": "<blank>",
"pageID": "Person",
"fieldName": "LASTNAME",
"content": "Steve",
"fieldCode": "1111"
}
]
Above JSON array show 2 objects (sample list) and each object having set of field in same order. It means, first node (questionaireType) is at root level.
For Other fields, previous values should refer as parent node in each if the parent node value is not <blank>. if the parent node is <blank> should go to next parent which is not <blank>.
Below, I have added comments in each line for explanation.
Please help me to generate JSON object for below kind of list to use in a angular tree (it means I need to generate nested child json array from this list).
"questionaireType": "Q_AUTO_APPLICATION", // root parent
"cardID": "<blank>", // should not consider as value is <blank>
"setID": "2", // should display as root parent's child as
// cardID is blank
"setName": "SET1", // setID & setName are in same object
"sectionID": "<blank>", //should not consider as value is <blank>
"sectionName": "<blank>", //should not consider as value is <blank>
"pageID": "Person", //pageID should come under setID as
//sectionID is <blank>
"fieldName": "FIRSTNAME", //fieldName,content & fieldCode are in same
//object and come under pageID
"content": "John",
"fieldCode": "1111"

Related

Usage of rest parameter with object

I am trying to pull the user information by passing some object values as rest parameter. Whenever I try to pass 2 arguments, the code throws an error (undefined). What is it that I am missing?
Here is the Jsfiddle link of what I am trying to do.
let userAddress = [{
"street": "someStreet1",
"house": "1",
"person": "User1"
}, {
"street": "someStreet2",
"house": "2",
"person": "User2"
}, {
"street": "someStreet3",
"house": "3",
"person": "User3"
}];
let userInfo = [];
let addressToCheck = (...newUserHouse) => {
for (let address of userAddress) {
if (newUserHouse == address.house) {
userInfo.push(address.person);
console.log(userInfo);
}
}
}
console.log(addressToCheck(3, 2));
EDIT
Additional info:
I had this problem in which I had a JSON data and I had to pass multiple values and check whether those values were present in the dataset or not and if present, display the whole object.
For example; In the userAddress Array (as shown above) I need to check if 3, 2 (passed as an argument) are present as house number in userAddress. If they are present, then display the whole information about that particular object. As in this case, since 3, 2 are valid house numbers, the expected result should be:
Object { "street": "someStreet2", "house": "2", "person": "User2" }
Object { "street": "someStreet3", "house": "3", "person": "User3" }
The code does not throw an undefined error, it simply logs the value undefined. And that happens because you are calling console.log on the return value of addressToCheck but the function doesn't return a value, so it implicitly returns undefined. See console.log returns an additional undefined.
However, there are more problems with your code. It only accidentally works when you pass a single argument because you are using loose comparison (==).
The value of a rest parameter is always an array. That means you are really doing the following comparisons:
[1, 2] == "1"
[1, 2] == "2"
[1, 2] == "3"
I hope it's obvious why this cannot work. An array with multiple elements cannot be equal to a single "element", so the if condition is never fulfilled.
It works accidentally with a single argument because the string representation of [1] is simply "1". The string representation if [1,2] however is "1,2".
You are not explaining what the desired outcome is but if you want to select all addresses for the provided input, you should be using .filter instead. And you can convert the provided arguments to a set for fast lookup.
Instead of assigning values to an "external" array, simply return the result from the function.
let userAddress = [{
"street": "someStreet1",
"house": "1",
"person": "User1"
}, {
"street": "someStreet2",
"house": "2",
"person": "User2"
}, {
"street": "someStreet3",
"house": "3",
"person": "User3"
}];
let addressToCheck = (...newUserHouse) => {
newUserHouse = new Set(newUserHouse);
return userAddress.filter(address => newUserHouse.has(address.house));
};
console.log(addressToCheck("3", "2"));
A functional way to achieve this using ES6 is to utilize the Array's filter() and includes() methods in a custom function, (namely getUsersMatchingHouseNumbers), as shown in the gist below:
const userData = [{
"street": "someStreet1",
"house": 1,
"person": "User1"
}, {
"street": "someStreet2",
"house": 2,
"person": "User2"
}, {
"street": "someStreet3",
"house": 3,
"person": "User3"
}]
function getUsersMatchingHouseNumbers(userData, ...houseNumbers) {
return userData.filter(({ house }) => houseNumbers.includes(house));
}
console.log(getUsersMatchingHouseNumbers(userData, 1, 3));
Notes
The userData.filter(({ house }) part uses Object destructuring to obtain only the house property/value from each userData object.
The getUsersMatchingHouseNumbers function returns an array of user objects whose house number matches those passed to the function when it is invoked.
In my code, I was missing out the point that rest parameters are an array of parameters and in order to manipulate them, we have to iterate over them too.
let userAddress = [{
"street": "someStreet1",
"house": 1,
"person": "User1"
}, {
"street": "someStreet2",
"house": 2,
"person": "User2"
}, {
"street": "someStreet3",
"house": 3,
"person": "User3"
}]
let addressToCheck = (...houses) => {
for(let house of houses){
for (let user of userAddress) {
if(user.house === house){
console.log(user);
break;
}
}
}
}
console.log(addressToCheck(1, 3));

Render Nested json objects in React Native

In my render() method i need to parse nested json objects. See the portion of render and json structure below.
I access Last Name with {params.name_last}.
How will i access items under team, like team.name_first
render() {
let { params } = this.props.navigation.state
<Text>{params.name_last}</Text>
}
[
{
"id": 1,
"name_first": "Name first 1",
"name_middle": "",
"name_last": "Name last 1",
"name_suffix": "",
"phone": "888-8888",
"fax": "888-8888",
"updated_at": "2015-11-02T21:42:42.000Z",
"team": [
{
"id": 16,
"name_first": "aaa",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
},
{
"id": 28,
"name_first": "aaa",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
},
{
"id": 29,
"name_first": "aaa ",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
}
]
}
]
Since team is an array, you need to either access a specific entry in the array, or iterate over the entire thing.
To reach a specific property in the nested array entry (assuming you want the object at index i):
params.team[i].name_first
To create an array of first names:
params.team.map(x => x.name_first)

JSON serialization technicalities in VB.NET

What is the difference between the following serialization methods?
First Method
JsonConvert.SerializeObject(list or datatable)
and the output is
i.e. (3) [Object, Object, Object]
Second Method
Dim parent = Prtdata
Dim lGridColumns = New With {
Key .data = parent
}
Dim Setting = New JsonSerializerSettings
Setting.PreserveReferencesHandling = PreserveReferencesHandling.Objects
Dim jsonObject = JsonConvert.SerializeObject(lGridColumns, Formatting.Indented)
Return jsonObject
and its output is
{
"data": [
{
"RecID": 2383,
"PrtStatus": 0,
"PtFilenum": 15090248,
"PrtFilenum": 13090701,
"FullName": "asdasd",
"DOB": "04 Oct 1985"
},
{
"RecID": 3387,
"PrtStatus": 1,
"PtFilenum": 15090248,
"PrtFilenum": 15120996,
"FullName": "marwam mohmmad saleem",
"DOB": "24 May 2017"
},
{
"RecID": 3388,
"PrtStatus": 1,
"PtFilenum": 15090248,
"PrtFilenum": 170227111,
"FullName": "asd dsf as a",
"DOB": "27 Feb 2017"
}
]
}
why the output looks different in the browser console?
As the first comment, you can find a Serialization Guide on the website of NewtonSoft.json, in my answer I just provide a more elaborate version of my comment earlier.
The first scenario, where you are serializing something implemented IEnumerable (eg: list, array), will be represented by an array in Json, eg:
[{ "property": "value", "id": 0 }, {"property": "value", "id": 1}]
For the second scenario, you are doing several things differently, for example you are providing the PreserveReferencesHandling in the JsonSerializerSettings which would also preveserve any references made in the objects you are serializing, eg:
[{"$id": 1, "title": "item1"}, {"$id": 2, "title": "item2", "previous": { "$ref": 1 }]
This would make sure that when deserialized, the second object would contain a reference to the first object, inside the property previous.
Another thing you are doing differently is providing the Formatting.Indented, which will create a more reader friendly json document, having line breaks and indentation. The previous Json would then become something similar to this:
[{
"$id": 1,
"title": "item1"
},
{
"$id": 2,
"title": "item2",
"previous": {
"$ref": 1
}
}]
And, the last big difference is that in the last example, you are serializing a single object, cause it's public properties to be serialized, eg:
{
"data": [
...
]
}
Where data is a property on the object you are serializing.

Rails 4: Trying to use Ancestry with jstree

I am new to Rails and trying to populate a jstree in the browser with JSON from the Ancestry gem (see https://github.com/stefankroes/ancestry). JSON is the go-between. Where I am stuck is translating the JSON produced (from my Tree model) by Ancestry:
<%= #trees.arrange_serializable.to_json %>
That gives me nice JSON as follows (fragment only, apologies for the nonsense values):
[
{
"id": 2,
"name": "Milk",
"note": "No details available",
"created_at": "2014-09-20T13:22:03.262Z",
"updated_at": "2014-09-20T13:48:46.301Z",
"value": "3.06",
"ancestry": null,
"children": [
{
"id": 1,
"name": "Farms",
"note": "Some note here",
"created_at": "2014-09-20T13:05:22.186Z",
"updated_at": "2014-10-03T11:30:39.029Z",
"value": "432.0",
"ancestry": "2",
"children": [
{
"id": 8,
"name": "Zog",
"note": "Orc",
"created_at": "2014-09-27T22:11:20.874Z",
"updated_at": "2014-10-03T11:30:38.989Z",
"value": "11.0",
"ancestry": "2/1",
"children": [
{
"id": 14,
"name": "Planes",
"note": "",
"created_at": "2014-10-04T01:01:12.890Z",
"updated_at": "2014-10-04T04:51:20.873Z",
"value": "422.0",
"ancestry": "2/1/8",
"children": []
}
]
},
but the jstree plugin requires a particular format for the JSON as follows (from http://www.jstree.com/docs/json/):
{
id : "string" // will be autogenerated if omitted
text : "string" // node text
icon : "string" // string for custom
state : {
opened : boolean // is the node open
disabled : boolean // is the node disabled
selected : boolean // is the node selected
},
children : [] // array of strings or objects
li_attr : {} // attributes for the generated LI node
a_attr : {} // attributes for the generated A node
}
While the source hierarchical structure is perfect, I need to replace the attribute "name" in the original with "text" in the output, plus a few other changes.
At the back of my mind I feel there should be something elegant (like XSLT for XML) to translate JSON#1 into JSON#2 but I can't find any examples that do this.

Json Slupper assert and extract

I'm using the next Json
{
"ID": 8,
"MenuItems": [
{
"ID": 38,
"Name": "Home",
"URL": "{\"PageLayout\":\"Home\",\"Icon\":\"home\"}",
"Culture": "en",
"Children": null
},
{
"ID": 534,
"Name": "GUIDE ",
"URL": "{''PageLayout'':''Page A'', ''Icon'':''A''}",
"MenuType": 1,
"PageID": 0,
"Culture": "en",
"Children": [
{
"ID": 6,
"Name": "Form A",
"URL": "[''Type'':''Form A'',''Icon'':''Form'',''ItemID'':\"358\"]",
"Culture": "he",
"RuleID": 0
},
{
"ID": 60,
"Name": "Drama",
"URL": "[''Type'':''Form B'',''Icon'':''Form'',''ItemID'':\"3759\"]",
"Culture": "en",
"RuleID": 0
}
]
}
]
}
i'm using Groovy script in soapUI and i need to:
Assert the exitance of node that has the name GUIDE
Extract a list of all Itemsid
You can parse the JSON content using JsonSlurper and then work with the results like so:
import groovy.json.JsonSlurper
// Assuming your JSON is stored in "jsonString"
def jsonContent = new JsonSlurper().parseText(jsonString)
// Assert node exists with name GUIDE
assert(jsonContent.MenuItems.Name.contains("GUIDE"))
// Get list of ItemIDs
def itemList = jsonContent.MenuItems.Children.URL.ItemID[0].toList()
// List the items
itemList.each {log.info it}
Note that the above will fail given your current example, because of a few issues. Firstly, Name contains "GUIDE " (trailing space) rather than "GUIDE" (so you will need to adapt accordingly). Secondly, it is invalid JSON; the URL nodes have various erroneous characters.
On a side note, if you first need to retrieve your JSON from the response associated with a previous TestStep (say one called "SendMessage") within the existing testCase, this can be done as follows:
def jsonString = context.testCase.getTestStepByName("SendMessage").testRequest.response.getContentAsString()