My experience with parsing JSON is fairly minimal but the document im working with is pretty big. JSON Objects are nested within one another and the keys are fairly consistent with "title","description","properties","default", and "type". Property/Object names will vary and new values may be added overtime so I want this to be as flexible as possible.
Here is a sample of the JSON I am working with, The real document is much larger:
{
"title": "settings schema",
"description": "Settings schema ",
"type": "object",
"properties": {
"alerts": {
"description": "Settings for alerts ",
"type": "object",
"properties": {
"pageSize": {
"description": "The number of alerts .",
"type": "number",
"default": 15
},
"paramKeys": {
"description": "parameter keys",
"type": "string",
"default": "fromKey,toKey,inKey,outKey"
},
"alertsEnabled": {
"description": "Enable/disable alerts",
"type": "boolean",
"default": true
},
"actionablesEnabled": {
"description": "Enable/disable actionable alerts",
"type": "boolean",
"default": true
},
"HistoryEnabled": {
"description": "Enable/disable alert history",
"type": "boolean",
"default": true
},
"generalAlertsEnabled": {
"description": "Enable/disable general alerts",
"type": "boolean",
"default": true
},
"accountsEnabled": {
"description": "Enable/disable account alerts",
"type": "boolean",
"default": true
},
"alertPrefsEnabled": {
"description": "Enable/disable alert preferences",
"type": "boolean",
"default": true
},
"datePicker": {
"description": "Search date picker settings",
"type": "object",
"properties": {
"maxSearchDays": {
"description": "The maximum days to search before today's date. Used on search page",
"type": "integer",
"default": 365
},
"minDays": {
"description": "The number of days before a user is able to select a date. Should be less than the maxDays",
"type": "integer",
"default": 0
},
"maxDays": {
"description": "The total number of days that user is able to select a date until. Should be greater than minDays",
"type": "integer",
"default": 30
},
"blackOutDays": {
"description": "Days of the week indicated by 0 (Sunday) though 6 (Saturday) that will be blacked out",
"type": "array",
"default": []
},
"blackOutDates": {
"description": "Date Ranges or individual dates in the following format: ['20 Mar 2014 - 1 May 2014', '28 Apr 2014'] that are blacked out or unselectable on the calendar. Typically holidays. ",
"type": "array",
"default": []
},
"isAlertCalendar": {
"description": "Configures datepicker to work for alerts dnd ",
"type": "boolean",
"default": true
}
},
"required": [
"maxSearchDays",
"minDays",
"maxDays",
"blackOutDays",
"blackOutDates",
"isAlertCalendar"
]
}
},
"required": [
"pageSize",
"paramKeys"
]
}
}
Ive seen a lot of places online say to iterate over arrays but it seems like im dealing with more nested Objects than arrays. Value/Property names may change so I cant really hardcode any property names. I am trying to pull this data and parse it back into an HTML table ideally leaving empty cells where data doesn't apply. For example the first column would have the "alerts" title and every cell underneath it would be empty until all of its properties had been parsed into the next column with property description/type/sub properties/ and defaults in the following columns again leaving blank values when there is no data to include.
Here is a hardcoded example of what I am trying to achieve
Ive never had to work with such complex dynamic json data before so usually its as easy as chaining together keys to get to values but this i really throwing me through a loop and the output i am producing looks like 200 empty cells with the word "id" repeated 10 times in the middle of it.
Any advice helps!
You need to know how deep your structure is in order to render x amount
of sub property columns ( where x is the number of levels )
When parsing an object you need to know the level where that object is so that you may add columns to that row corresponding to that object.
use recursion. Since you know what type you're dealing with you only have to recurse down the properties with the type object.
I honestly tried solving your problem but I keep bumping to the problem that this table is going to look horrific after 3+ levels. I would perhaps rethink how you want the data to be displayed.
If this is some sort of exercise ( i.e. you have to use a table ) I would look into a js template rendering engine that would help you render the x columns. i.e. something like underscore would let you do:
<tr>
<% for(var i = 0; i < totalNumberOfLevels; i --) { %>
<td></td>
<% }; %>
<td><%- default %></td>
</tr>
Maybe this helps you out?
Convert JSON array to an HTML table in jQuery
(at the download page is also a module listed which supports sub grid creation)
http://www.trirand.com/blog/?page_id=6
Related
I have a collection named templates. It has a field 'sec_1' which is an array of objects with properties 'name' and 'des' both of type string. Now I'm using elastic search and when I try to execute a query that matches only title fields I get an error saying the sec_1 field is not nested. Upon checking the mappings here is what I get mapping type of sec_1 is text.
I checked online and saw the fix was to modify the mapping. I created a new index like:
`curl base_url/new_index_name
{
"mappings":
{"properties": {
"sec_1": {
"type":
"nested","properties": {
"name": { "type": "text" },
"des": { "type": "text" }
}
}
}
}
}
and then reindexed like this:
curl base_url/_reindex
{
"source": {
"index": "old_index"
},
"dest": {
"index": "new_index"
}
}`
First request is successful, the second one fails with this error:
{
"index": "new_index",
"type": "_doc",
"id": "be5123a4-d0e8-4d7b-a8f1-42f31d37fe55",
"cause": {
"type": "mapper_parsing_exception",
"reason": "object mapping for [sec_1] tried to parse field [null] as object, but found a concrete value"
},
"status": 400
},
I don't understand why this is happening and what I'm doing wrong. Please help. I do not know much about elastic search, I've looked for solutions online, tried chatgpt too but the same steps appear. I'm finding the reason for this error is that sec_1 is not nested type but I've checked in database it is an array of objects. What else could be wrong?
I tried creaing new index but cannot do that and without new index my search query cant function properly
I have an Alpaca JS form comprised of an array of items which each consist of a textbox and a checkbox. For some reason, when I change the order using the dynamic controls, it successfully renumbers the textbox but doesn't change the number of the checkbox. This also results in a duplicate name assigned if the same top button to dynamically add new fields is pressed. The end result is incorrect data being passed when the form is submitted. How can I fix this to properly renumber the checkboxes?
Here's a sample of the Alpaca configuration:
$("#form1").alpaca({
"schema": {
"title": "Testing checkbox array IDs",
"description": "Testbox checkbox array test.",
"type": "object",
"properties": {
"form-fields": {
"title": "Fields",
"description": "These are the fields.",
"type": "array",
"items": {
"type": "object",
"properties": {
"field-name": {
"type": "string",
"title": "Field Name",
"description": "Enter the name for this field.",
"required": true
},
"field-box": {
"type": "boolean",
"title": "Field Box",
"description": "Check this box.",
"default": false
}
}
}
}
}
}
});
I couldn't find a way to correct the behavior itself but I was able to work around it by adding a postRender event to the Alpaca definition as follows:
"postRender": function(control) {
control.childrenByPropertyId["form-fields"].on("move", function() { $('input[type=checkbox]').each(function(index) { $(this).attr("name", $(this).closest("div:has(*[name])").first().attr("name")) }); });
control.childrenByPropertyId["form-fields"].on("add", function() { $('input[type=checkbox]').each(function(index) { $(this).attr("name", $(this).closest("div:has(*[name])").first().attr("name")) }); });
control.childrenByPropertyId["form-fields"].on("remove", function() { $('input[type=checkbox]').each(function(index) { $(this).attr("name", $(this).closest("div:has(*[name])").first().attr("name")) }); });
}
This is a bit of a hack but it works because the parent object does get assigned the correct name value and the form will post with those values if the name is just copied down into the input elements.
I'm working on creating my own schematics. This schematics will be responsible for creating a component (container) with some code. Template of this component will contain a few other components. One of this component will be banner component that will be optional. This banner will display text that will be translated into other languages, so I also should ask the user to provide (default) translation text if the banner will be included in the component.
Here is an example of this template:
name#dasherize.component.html.template:
<% if (includeBanner) { %>
<app-banner [title]="'<%= translationModuleKey %>.banner.title' | translate"
[description]="'<%= translationModuleKey %>.banner.description' | translate">
</app-banner>
<% } %>
<app-other-component>
</app-other-component>
Here is my schema.json:
{
"$schema": "http://json-schema.org/schema",
"id": "MySchematics",
"title": "My schematics",
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The name of the container",
"x-prompt": "Container name"
},
"includeBanner": {
"type": "boolean",
"description": "Include banner",
"default": "true",
"x-prompt": "Include banner"
},
"bannerTitle": {
"type": "string",
"description": "Banner title",
"x-prompt": "Banner title"
},
"bannerDescription": {
"type": "string",
"description": "Banner description",
"x-prompt": "Banner description"
},
"translationModuleKey": {
"type": "string",
"description": "Root key for translations"
}
},
"required": [
"name", "includeBanner", "bannerTitle", "bannerDescription"
]
}
My problem is that when user will set includeBanner to true, fields bannerTitle and bannerDescription should be required and there should be displayed prompt if those properties were not provided, but if includeBanner will be false, bannerTitle and bannerDescription shouldn't be required and there shouldn't be displayed prompt to fill these properties if those properties were not provided.
Any idea how to achieve that?
I was struggling with the same problem. What I've discovered - if you need conditional prompts, then you can't rely on declarative schema.json file (it doesn't support conditions).
Instead, you should use the askConfirmation function from #angular/cli/utilities/prompt.
So your example could look like this:
import { askConfirmation } from '#angular/cli/utilities/prompt';
export function yourSchematicsFn(options: Schema): Rule {
return async (tree: Tree, context: SchematicContext) => {
const includeBanner = await askConfirmation('Include Banner?', true);
if(includeBanner) {
// ask for bannerTitle and bannerDescription
}
else {
// do something else
}
return chain(/* chain your rules here */);
}
}
I've discovered this in Angular CLI ng-add schematics source code: askConfirmation.
I need help because I'm losing my mind haha ...
I have the main array products with this (it's just a sample) :
[
{
"from": "country",
"maker": "name of maker",
"id": "1969",
"image": "image.jpg",
"label": "355",
"name": "name of product",
"price": "12.90",
"subscriber_price": "8.90",
"url_path": "url",
"occasion": null,
"colour": "31",
"origin": "397",
},
{
"from": "country",
"maker": "name of maker",
"id": "2043",
"image": "image.jpg",
"label": "362",
"name": "name of product",
"price": "24.90",
"subscriber_price": "24.90",
"url_path": "url",
"occasion": "51,376,155,39",
"colour": "31",
"origin": "395"
}
]
I'm working this the Picker Component. So, what I'm doing is :
I have a Picker to select products with their "colour".. then I have another one to filter the selected products (only with colour:31 for example) with their "origin" and finally I want to filter them through their "label" ...
The fact is I have 3 Pickers, 3 functions to select them and it's working but the problem is I'm erasing with a setState my render of "displayProducts". So, when I have selected the 3 options, I can't go back..
For example, I choose "colour:31" with "origin:397" and "label:355" .. I can't go back and tell : finally I want "origin:395" because it doesn't exist anymore, etc... and one "colour" can have different "label, origin, ..."
I'm doing something like this but it's only available for ONE option and not multiple options and without keeping a solution to find again my filtered products :
onChangeGetOrigin(originValue) {
this.setState(() => ({
activeOrigin: originValue,
displayProducts: this.state.displayProducts.filter(product => product.origin == originValue)
}));
}
Do anyone can understand what I'm saying ? :-D
You can maintain two arrays. One contains the complete list of products and the other one is a derived array after applying the filters. You can use the derived list for display and original array for selection.
I am building a website to help operator of my team to generate a data source config.
Since there are many options need to be handled. I design an common solution to render the page: parse a config file(maybe, xml or json format) to html with some rules. Maybe something like below:
{
"data_type": {
"title": "Data type",
"description": "Select what type do you want.",
"fields": [{
"title": "promotion",
"description": "data from promotion center"
"type": "redio",
"default": true,
"value": "p",
"name": "dtype"
}, {
"title": "brands",
"description": "data from brands center"
"type": "redio",
"default": false,
"value": "b",
"name": "dtype"
}]
}
}
then it can be parsed as:
<div class="form-control-group">
<h3>Data type</h3>
<p>Select what type do you want.</p>
<div class="form-control-filed">
<input type="redio" name="dtype" value="p" show="dtype" checked />
<p>data from promotion center</p>
</div>
<div class="form-control-filed">
<input type="redio" name="dtype" value="b" />
<p>data from brands center</p>
</div>
</div>
This step is easily to implement. But since there are some cases like. When I click redio A, I wanna hide the checkbox B. After I unchecked Checkbox C, I wanna show up the input D. I have no idea about how to design the config file to describe the logic about different fields.
So, the key point is, I wanna parse the html by a json snippet. Then maybe there are some symbols to mark the behavior of each form field, I can use my common js to bind events to handle the show/hide, focus/blur or something else logic. Like the attribute show, I can use my common js function to detect it and bind click event to that radio button, and show up the element with name="dtype" after this radio is clicked.
I am not sure if it is a good solution and how to design an reasonable json structure.
Hope any one can provide some suggestions. Thanks in advance.
I've given up for this case. For my requirement, I use a json file to config the information of the form field with a behavior definition to describe show/hide functionality.
{
"xxx": {
"title": "Price mode",
"description": "group_description",
"fields": [{
"title": "",
"type": "select",
"name": "price_mode",
"value": [{
"text": "Store with product",
"value": 1,
"default": true,
"behaviors": {
"show": "name1|name2|name3",
"hide": ""
}
}, {
"text": "Product",
"value": 2,
"default": false,
"behaviors": {
"show": "",
"hide": "name1|name2|name3"
}
}],
"require": true,
"rule": ""
}]
}
}
Codes of server side will parse this config and render as html snippet with special attribute storing behavior definition, then use javascript functions handle these attributes and care about the behavior after doing something like click the radio button or change the value of select list.