How to parser JSON and add some custom strings? - json

I have a JSON which come from spark:
val df = spark.read.parquet("hdfs://xxx-namespace/20190311")
val jsonStr = df.schema.json
jsonStr is like this:
{
"type":"struct",
"fields":[
{
"name":"alm_dm_list",
"type":{
"type":"array",
"elementType":"integer",
"containsNull":true
},
"nullable":true,
"metadata":{
}
},
{
"name":"data_batt_sc_volt_lowest",
"type":"double",
"nullable":true,
"metadata":{
}
},
{
"name":"veh_dcdcst",
"type":"integer",
"nullable":true,
"metadata":{
}
},
{
"name":"esd_temp_data",
"type":{
"type":"array",
"elementType":{
"type":"struct",
"fields":[
{
"name":"esd_temp_probe_cnt",
"type":"integer",
"nullable":true,
"metadata":{
}
},
{
"name":"esd_temp_probe_list",
"type":{
"type":"array",
"elementType":"integer",
"containsNull":true
},
"nullable":true,
"metadata":{
}
},
{
"name":"esd_temp_subsys_seq",
"type":"integer",
"nullable":true,
"metadata":{
}
}
]
},
"containsNull":true
},
"nullable":true,
"metadata":{
}
},
{
"name":"esd_volt_data",
"type":{
"type":"array",
"elementType":{
"type":"struct",
"fields":[
{
"name":"esd_curr",
"type":"double",
"nullable":true,
"metadata":{
}
},
{
"name":"esd_frame_sc_cnt",
"type":"integer",
"nullable":true,
"metadata":{
}
},
{
"name":"esd_frame_sc_list",
"type":{
"type":"array",
"elementType":"double",
"containsNull":true
},
"nullable":true,
"metadata":{
}
},
{
"name":"esd_frame_start",
"type":"integer",
"nullable":true,
"metadata":{
}
},
{
"name":"esd_sc_cnt",
"type":"integer",
"nullable":true,
"metadata":{
}
},
{
"name":"esd_volt",
"type":"double",
"nullable":true,
"metadata":{
}
},
{
"name":"esd_volt_subsys_seq",
"type":"integer",
"nullable":true,
"metadata":{
}
}
]
},
"containsNull":true
},
"nullable":true,
"metadata":{
}
},
{
"name":"dm_data",
"type":{
"type":"array",
"elementType":{
"type":"struct",
"fields":[
{
"name":"dm_ctl_dc_curr",
"type":"double",
"nullable":true,
"metadata":{
}
},
{
"name":"dm_ctl_temp",
"type":"integer",
"nullable":true,
"metadata":{
}
},
{
"name":"dm_ctl_volt",
"type":"double",
"nullable":true,
"metadata":{
}
},
{
"name":"dm_seq",
"type":"integer",
"nullable":true,
"metadata":{
}
},
{
"name":"dm_spd",
"type":"integer",
"nullable":true,
"metadata":{
}
},
{
"name":"dm_st",
"type":"integer",
"nullable":true,
"metadata":{
}
},
{
"name":"dm_temp",
"type":"integer",
"nullable":true,
"metadata":{
}
},
{
"name":"dm_torq",
"type":"integer",
"nullable":true,
"metadata":{
}
}
]
},
"containsNull":true
},
"nullable":true,
"metadata":{
}
}]
}
I want to get a scheme based on the JSON string, so i need to parse it and get a struct like this:
val schema = new StructType()
.add("alm_dm_list", ArrayType(IntegerType, true), true)
.add("data_batt_sc_volt_lowest", DoubleType, true)
.add("veh_dcdcst", IntegerType, true)
.add("esd_temp_data", ArrayType(new StructType()
.add("esd_temp_probe_cnt", IntegerType, true)
.add("esd_temp_probe_list", ArrayType(IntegerType, true), true)
.add("esd_temp_subsys_seq", IntegerType, true)
), true)
.add("esd_volt_data", ArrayType(new StructType()
.add("esd_curr", DoubleType, true)
.add("esd_frame_sc_cnt", IntegerType, true)
.add("esd_frame_sc_list", ArrayType(DoubleType, true), true)
.add("esd_frame_start", IntegerType, true)
.add("esd_sc_cnt", IntegerType, true)
.add("esd_volt", DoubleType, true)
.add("esd_volt_subsys_seq", IntegerType, true)
), true)
.add("dm_data", ArrayType(new StructType()
.add("dm_ctl_dc_curr", DoubleType, true)
.add("dm_ctl_temp", IntegerType, true)
.add("dm_ctl_volt", DoubleType, true)
.add("dm_seq", IntegerType, true)
.add("dm_spd", IntegerType, true)
.add("dm_st", IntegerType, true)
.add("dm_temp", IntegerType, true)
.add("dm_torq", IntegerType, true)
), true)
JSON::Infer maybe helpful, but there are nested structures in my JSON, which is complex for me, any suggestions will help.

In case you do not care about identing (possible, but not so important, what about this ?) does not work in IE - guess template strings are only problem(?):
'use strict';
function run() {
buildRecursive(2);
res = res.substr(0, res.length-1) + ';';
console.log(res);
}
var typeRename = {
"array": "ArrayType",
"double": "DoubleType",
"integer": "IntegerType"
}, elementRename = {
"integer": "IntegerType",
"double": "DoubleType"
}
var res = "val schema = ";
function repeatIndent(no) {
var retVal = '';
while(no--) retVal += ' ';
return retVal;
}
function buildRow(indent, params) {
return repeatIndent(indent) + params.join('');
}
function buildRecursive(indent) {
var lev = it.ReadArray(), indentStep = 1;
if(lev.type == "struct") {
res += "new StructType()\n";
var under = lev.fields;
while(under && under.node) {
it.SetCurrent(under.node);
buildRecursive(indent + indentStep);
under = under.next;
}
} else if (lev.name) {
if(lev.type instanceof JNode) {
it.SetCurrent(lev.type.node);
var lev2 = it.ReadArray();
it.DepthFirst();
var elementType = it.FindKey("elementType");
if(elementType.value instanceof Object) {
res += buildRow(indent, ['.add("', lev.name, '", ', typeRename[lev2.type], '(']);
var here = it.Current;
it.SetCurrent(elementType.node);
buildRecursive(indent + indentStep);
it.SetCurrent(here);
res += buildRow(indent,['), ', lev.nullable, ')\n']);
} else res += buildRow(indent, ['.add("', lev.name, '", ', typeRename[lev2.type], '(',
elementRename[elementType.value], ', ', lev2.containsNull, '), ', lev.nullable, ')\n']);
} else {
res += buildRow(indent, ['.add("', lev.name, '", ', typeRename[lev.type], ', ', lev.nullable, ')\n']);
}
}
}
// My JSON iterator
var JNode = (function (jsNode) {
function JNode(_parent, _pred, _key, _value) {
this.parent = _parent;
this.pred = _pred;
this.node = null;
this.next = null;
this.key = _key;
this.value = _value;
}
return JNode;
})();
var JIterator = (function (json) {
var root, current, maxLevel = -1;
function JIterator(json, parent) {
if (parent === undefined) parent = null;
var pred = null, localCurrent;
for (var child in json) {
var obj = json[child] instanceof Object;
if(json instanceof Array) child = parseInt(child); // non-associative array
if (!root) root = localCurrent = new JNode(parent, null, child, json[child]);
else {
localCurrent = new JNode(parent, pred, child, obj ? ((json[child] instanceof Array) ? [] : {}) : json[child]);
}
if (pred) pred.next = localCurrent;
if (parent && parent.node == null) parent.node = localCurrent;
pred = localCurrent;
if (obj) {
var memPred = pred;
JIterator(json[child], pred);
pred = memPred;
}
}
if (this) {
current = root;
this.Level = 0;
}
}
JIterator.prototype.Current = function () { return current; }
JIterator.prototype.SetCurrent = function (newCurrent) { current = newCurrent; }
JIterator.prototype.Parent = function () {
var retVal = current.parent;
if (retVal == null) return false;
this.Level--;
return current = retVal;
}
JIterator.prototype.Pred = function () {
var retVal = current.pred;
if (retVal == null) return false;
return current = retVal;
}
JIterator.prototype.Node = function () {
var retVal = current.node;
if (retVal == null) return false;
this.Level++;
return current = retVal;
}
JIterator.prototype.Next = function () {
var retVal = current.next;
if (retVal == null) return false;
return current = retVal;
}
JIterator.prototype.Key = function () { return current.key; }
JIterator.prototype.KeyDots = function () { return (typeof(current.key) == "number")?"":(current.key+':'); }
JIterator.prototype.Value = function () { return current.value; }
JIterator.prototype.Reset = function () {
current = root;
this.Level = 0;
}
JIterator.prototype.RawPath = function () {
var steps = [], level = current;
do {
if (level != null && level.value instanceof Object) {
steps.push(level.key + (level.value instanceof Array ? "[]" : "{}"));
} else {
if (level != null) steps.push(level.key);
else break;
}
level = level.parent;
} while (level != null);
var retVal = "";
retVal = steps.reverse();
return retVal;
}
JIterator.prototype.Path = function () {
var steps = [], level = current;
do {
if (level != null && level.value instanceof Object) {
var size = 0;
var items = level.node;
if(typeof(level.key) == "number") steps.push('[' + level.key + ']');
else {
while(items) {
size++;
items = items.next;
}
var type = (level.value instanceof Array ? "[]" : "{}");
var prev = steps[steps.length-1];
if(prev && prev[0] == '[') {
var last = prev.length-1;
if(prev[last] == ']') {
last--;
if(!isNaN(prev.substr(1, last))) {
steps.pop();
size += '.' + prev.substr(1, last);
}
}
}
steps.push(level.key + type[0] + size + type[1]);
}
} else {
if (level != null) {
if(typeof(level.key) == "number") steps.push('[' + level.key + ']');
else steps.push(level.key);
}
else break;
}
level = level.parent;
} while (level != null);
var retVal = "";
retVal = steps.reverse();
return retVal;
}
JIterator.prototype.DepthFirst = function () {
if (current == null) return 0; // exit sign
if (current.node != null) {
current = current.node;
this.Level++;
if (maxLevel < this.Level) maxLevel = this.Level;
return 1; // moved down
} else if (current.next != null) {
current = current.next;
return 2; // moved right
} else {
while (current != null) {
if (current.next != null) {
current = current.next;
return 3; // returned up & moved next
}
this.Level--;
current = current.parent;
}
}
return 0; // exit sign
}
JIterator.prototype.BreadthFirst = function () {
if (current == null) return 0; // exit sign
if (current.next) {
current = current.next;
return 1; // moved right
} else if (current.parent) {
var level = this.Level, point = current;
while (this.DepthFirst() && level != this.Level);
if (current) return 2; // returned up & moved next
do {
this.Reset();
level++;
while (this.DepthFirst() && level != this.Level);
if (current) return 3; // returned up & moved next
} while (maxLevel >= level);
return current != null ? 3 : 0;
} else if (current.node) {
current = current.node;
return 3;
} else if (current.pred) {
while (current.pred) current = current.pred;
while (current && !current.node) current = current.next;
if (!current) return null;
else return this.DepthFirst();
}
}
JIterator.prototype.ReadArray = function () {
var retVal = {};
var item = current;
do {
if(item.value instanceof Object) {
if(item.value.length == 0) retVal[item.key] = item.node;
else retVal[item.key] = item;
} else retVal[item.key] = item.value;
item = item.next;
} while (item != null);
return retVal;
}
JIterator.prototype.FindKey = function (key) {
var pos = current;
while(current && current.key != key) this.DepthFirst();
if(current.key == key) {
var retVal = current;
current = pos;
return retVal;
} else {
current = pos;
return null;
}
}
return JIterator;
})();
var json = {
"type": "struct",
"fields": [
{
"name": "alm_dm_list",
"type": {
"type": "array",
"elementType": "integer",
"containsNull": true
},
"nullable": true,
"metadata": {}
},
{
"name": "data_batt_sc_volt_lowest",
"type": "double",
"nullable": true,
"metadata": {}
},
{
"name": "veh_dcdcst",
"type": "integer",
"nullable": true,
"metadata": {}
},
{
"name": "esd_temp_data",
"type": {
"type": "array",
"elementType": {
"type": "struct",
"fields": [
{
"name": "esd_temp_probe_cnt",
"type": "integer",
"nullable": true,
"metadata": {}
},
{
"name": "esd_temp_probe_list",
"type": {
"type": "array",
"elementType": "integer",
"containsNull": true
},
"nullable": true,
"metadata": {}
},
{
"name": "esd_temp_subsys_seq",
"type": "integer",
"nullable": true,
"metadata": {}
}
]
},
"containsNull": true
},
"nullable": true,
"metadata": {}
},
{
"name": "esd_volt_data",
"type": {
"type": "array",
"elementType": {
"type": "struct",
"fields": [
{
"name": "esd_curr",
"type": "double",
"nullable": true,
"metadata": {}
},
{
"name": "esd_frame_sc_cnt",
"type": "integer",
"nullable": true,
"metadata": {}
},
{
"name": "esd_frame_sc_list",
"type": {
"type": "array",
"elementType": "double",
"containsNull": true
},
"nullable": true,
"metadata": {}
},
{
"name": "esd_frame_start",
"type": "integer",
"nullable": true,
"metadata": {}
},
{
"name": "esd_sc_cnt",
"type": "integer",
"nullable": true,
"metadata": {}
},
{
"name": "esd_volt",
"type": "double",
"nullable": true,
"metadata": {}
},
{
"name": "esd_volt_subsys_seq",
"type": "integer",
"nullable": true,
"metadata": {}
}
]
},
"containsNull": true
},
"nullable": true,
"metadata": {}
},
{
"name": "dm_data",
"type": {
"type": "array",
"elementType": {
"type": "struct",
"fields": [
{
"name": "dm_ctl_dc_curr",
"type": "double",
"nullable": true,
"metadata": {}
},
{
"name": "dm_ctl_temp",
"type": "integer",
"nullable": true,
"metadata": {}
},
{
"name": "dm_ctl_volt",
"type": "double",
"nullable": true,
"metadata": {}
},
{
"name": "dm_seq",
"type": "integer",
"nullable": true,
"metadata": {}
},
{
"name": "dm_spd",
"type": "integer",
"nullable": true,
"metadata": {}
},
{
"name": "dm_st",
"type": "integer",
"nullable": true,
"metadata": {}
},
{
"name": "dm_temp",
"type": "integer",
"nullable": true,
"metadata": {}
},
{
"name": "dm_torq",
"type": "integer",
"nullable": true,
"metadata": {}
}
]
},
"containsNull": true
},
"nullable": true,
"metadata": {}
}
]
};
var it = new JIterator(json);
run();

Related

JSON Transformation to required format

We are working on a Middleware platform where we are required to respond to consumer with a JSON data in a particular format.
The Data we get from south bound API is a key value pair and this needs to be mapped to an understandable format for the consumer
We tried json-path, ObjectMapper but none of them is giving us the expected result for transforming
Respnse from backend API
{
"details": [
{
"name": "x.y.z.name","value": "TR-54695"
},
{
"name": "a.b.c.standards","value": "DOCSIS"
},
{
"name": "x.x.x.hversion","value": "10"
},
{
"name": "x.x.x.sversion","value": "9.1.116V"
},
{
"name": "x.x.x.uptime","value": "8000"
},
{
"name": "x.x.x.accessallowed","value": "true"
},
]
}
To be transformed to
{
"myData": {
"myInfo": {
"productClass": "TR-54695",
"supportedStandards": "DOCSIS",
"hardwareVersion": "10",
"softwareVersion": "9.1.116V",
"modemMacAddress": "",
"upTime": "8000",
"modemNetworkAccessAllowed": true
}
}
}
Do not like manual work, so here generated demo using 2 functions.
Mind ticking accept button under voting in case you like some answer.
function translate(src, mapping) {
var dst = { "myData": { "myInfo": { "modemMacAddress": "" } } }
//in case order matters:
dst = { "myData": { "myInfo": { "productClass": "", "supportedStandards": "", "hardwareVersion": "", "softwareVersion": "", "modemMacAddress": "", "upTime": "", "modemNetworkAccessAllowed": undefined } } }
var trueFalse = { "false": false, "true": true };
src = src.details;
for (var i = 0; i < src.length; i++) {
dst.myData.myInfo[mapping[src[i].name]] = trueFalse[src[i].value] || src[i].value;
}
return dst;
}
function generateMapping(src, dst) {
src = src.details;
var backLinks = {}, rename2 = {};
for (var i = 0; i < src.length; i++) {
backLinks[src[i].value] = src[i].name;
}
dst = dst.myData.myInfo;
for (var i in dst) {
rename2[backLinks[dst[i]]] = i;
}
return rename2;
}
var src = {
"details": [
{ "name": "x.y.z.name", "value": "TR-54695" },
{ "name": "a.b.c.standards", "value": "DOCSIS" },
{ "name": "x.x.x.hversion", "value": "10" },
{ "name": "x.x.x.sversion", "value": "9.1.116V" },
{ "name": "x.x.x.uptime", "value": "8000" },
{ "name": "x.x.x.accessallowed", "value": "true" },
]
}
var dst = {
"myData": {
"myInfo": {
"productClass": "TR-54695",
"supportedStandards": "DOCSIS",
"hardwareVersion": "10",
"softwareVersion": "9.1.116V",
"modemMacAddress": "",
"upTime": "8000",
"modemNetworkAccessAllowed": true
}
}
}
var mapping = generateMapping(src, dst);
// var mapping = {
// "x.y.z.name": "productClass",
// "a.b.c.standards": "supportedStandards",
// "x.x.x.hversion": "hardwareVersion",
// "x.x.x.sversion": "softwareVersion",
// "undefined": "modemMacAddress",
// "x.x.x.uptime": "upTime",
// "x.x.x.accessallowed": "modemNetworkAccessAllowed"
// }
var result = translate(src, mapping);
console.log(JSON.stringify(result, null, 2));
console.log(JSON.stringify(mapping, null, 2));
You can use below code and use codesandbox link (check console output ) for exact response and this link for key:value pair.
let response = {
details: [
{
name: "x.y.z.name",
value: "TR-54695"
},
{
name: "a.b.c.standards",
value: "DOCSIS"
},
{
name: "x.x.x.hversion",
value: "10"
},
{
name: "x.x.x.sversion",
value: "9.1.116V"
},
{
name: "x.x.x.uptime",
value: "8000"
},
{
name: "x.x.x.accessallowed",
value: "true"
}
]
};
// convert function for key value pair
function convertResponse(responseData) {
let output = { myData: { myInfo: {} } };
let outputRef = output.myData.myInfo;
responseData.forEach(element => {
outputRef[element.name] = element.value
});
return output;
}
// OR convert Function for getting exact same output
function convertResponse(responseData) {
let output = { myData: { myInfo: {} } };
let outputRef = output.myData.myInfo;
responseData.forEach(element => {
if (element.name === "x.y.z.name") {
outputRef.productClass = element.value;
} else if (element.name === "a.b.c.standards") {
outputRef.supportedStandards = element.value;
} else if (element.name === "x.x.x.hversion") {
outputRef.hardwareVersion = element.value;
} else if (element.name === "x.x.x.sversion") {
outputRef.softwareVersion = element.value;
} else if (element.name === "x.x.x.uptime") {
outputRef.upTime = element.value;
} else if (element.name === "x.x.x.accessallowed") {
outputRef.modemNetworkAccessAllowed = element.value;
}
});
return output;
}
//Function Call
console.log(convertResponse(response.details));

Explode Deeply Nested JSON returning duplicates in Spark Scala

I have a utility which is working fine for parsing simple JSONs, but cross joining in case multiple array[structs] is present in the JSON
I have tried distinct() or dropDuplicates() as well to remove duplicates which is happening due to the cross join that I have included in the code, but thats returning empty DF..
def flattenDataFrame(df: DataFrame): DataFrame = {
var flattenedDf: DataFrame = df
if (isNested(df)) {
val flattenedSchema: Array[(Column, Boolean)] = flattenSchema(df.schema)
var simpleColumns: List[Column] = List.empty[Column]
var complexColumns: List[Column] = List.empty[Column]
flattenedSchema.foreach {
case (col, isComplex) => {
if (isComplex) {
complexColumns = complexColumns :+ col
} else {
simpleColumns = simpleColumns :+ col
}
}
}
var crossJoinedDataFrame = df.select(simpleColumns: _*)
complexColumns.foreach(col => {
crossJoinedDataFrame = crossJoinedDataFrame.crossJoin(df.select(col))
crossJoinedDataFrame = flattenDataFrame(crossJoinedDataFrame)
})
crossJoinedDataFrame
} else {
flattenedDf
}
}
private def flattenSchema(schema: StructType, prefix: String = null): Array[(Column, Boolean)] = {
schema.fields.flatMap(field => {
val columnName = if (prefix == null) field.name else prefix + "." + field.name
field.dataType match {
case arrayType: ArrayType => {
val cols: Array[(Column, Boolean)] = Array[(Column, Boolean)](((explode_outer(col(columnName)).as(columnName.replace(".", "_"))), true))
cols
}
case structType: StructType => {
flattenSchema(structType, columnName)
}
case _ => {
val columnNameWithUnderscores = columnName.replace(".", "_")
val metadata = new MetadataBuilder().putString("encoding", "ZSTD").build()
Array(((col(columnName).as(columnNameWithUnderscores, metadata)), false))
}
}
}).filter(field => field != None)
}
def isNested(df: DataFrame): Boolean = {
df.schema.fields.flatMap(field => {
field.dataType match {
case arrayType: ArrayType => {
Array(true)
}
case mapType: MapType => {
Array(true)
}
case structType: StructType => {
Array(true)
}
case _ => {
Array(false)
}
}
}).exists(b => b)
}
A sample JSON in which I am facing the issue:
[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
{
"id": "0002",
"type": "donut",
"name": "Raised",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
]
Solution without join and more than that, no cross-join which is your problem:
Sorry for the formatting, can't really get it to format well for stack-overflow
def flattenDataFrame(df: DataFrame): DataFrame = {
val flattenedDf: DataFrame = df
if (isNested(df)) {
val flattenedSchema: Array[(Column, Boolean)] = flattenSchema(flattenedDf.schema)
var simpleColumns: List[Column] = List.empty[Column]
var complexColumns: List[Column] = List.empty[Column]
flattenedSchema.foreach {
case (col, isComplex) =>
if (isComplex) {
complexColumns = complexColumns :+ col
} else {
simpleColumns = simpleColumns :+ col
}
}
val complexUnderlyingCols = complexColumns.map { column =>
val name = column.expr.asInstanceOf[UnresolvedAttribute].name
val unquotedColName = s"${name.replaceAll("`","")}"
val explodeSelectColName = s"`${name.replaceAll("`","")}`"
(unquotedColName, col(name).as(unquotedColName), explode_outer(col(explodeSelectColName)).as(unquotedColName))
}
var joinDataFrame = flattenedDf.select(simpleColumns ++ complexUnderlyingCols.map(_._2): _*)
complexUnderlyingCols.foreach { case (name, tempCol, column) =>
val nonTransformedColumns = joinDataFrame.schema.fieldNames.diff(List(name)).map(fieldName => s"`${fieldName.replaceAll("`", "")}`").map(col)
joinDataFrame = joinDataFrame.select(nonTransformedColumns :+ column :_*)
}
flattenDataFrame(joinDataFrame)
} else {
flattenedDf
}
}
private def flattenSchema(schema: StructType, prefix: String = null, level: Int = 0): Array[(Column, Boolean)] = {
val unquotedPrefix = if (prefix != null) prefix.replace("", "") else null
println(level)
schema.fields.flatMap(field => {
val fieldName = field.name
val columnName = if (level == 0) {
s"$fieldName"
} else {
val fullName = s"$unquotedPrefix.$fieldName"
val x = fullName.split('.').reverse.zipWithIndex.reverse.foldLeft(new StringBuilder("")){ case (builder, (fieldPart, index)) =>
if(index > level) {
builder.append(s".$fieldPart")
} else if (index == level) {
builder.append(s".$fieldPart")
} else {
builder.append(s".$fieldPart")
}
}
x.replace(1,2,"").toString()
}
val unquotedColumnName = columnName.replace("", "")
field.dataType match {
case _: ArrayType =>
val cols: Array[(Column, Boolean)] = Array[(Column, Boolean)]((col(columnName), true)) // We pass only the column as we'll generate explode function while expanding the DF
cols
case structType: StructType =>
flattenSchema(structType, columnName, level + 1)
case _ =>
val metadata = new MetadataBuilder().putString("encoding", "ZSTD").build()
Array((col(columnName).as(unquotedColumnName, metadata), false))
}
})
}
def isNested(df: DataFrame): Boolean = {
df.schema.fields.flatMap(field => {
field.dataType match {
case _: ArrayType =>
Array(x = true)
case _: MapType =>
Array(x = true)
case _: StructType =>
Array(x = true)
case _ =>
Array(x = false)
}
}).exists(b => b)
}

Angular/Ionic - How to group data from two JSON source?

I want to group data JSON into accordion list in Ionic. How can I do that with two JSON source?
Previously I did successfully with only one JSON.
I have two JSON that look like this.
The one :
{
{
"ObjectId": '001',
"ObjectName": 'Fruits'
},
{
"ObjectId": '002',
"ObjectName": 'Vegetables'
}
}
The other one :
{
{
"Name": 'Apple',
"Color": 'Red',
"ObjectId": '001'
},
{
"Name": 'Eggplant',
"Color": 'Purple',
"ObjectId": '002'
},
{
"Name": 'Banana',
"Color": 'Yellow',
"ObjectId": '001'
},
{
"Name": 'Spinach',
"Color": 'Green',
"ObjectId": '002'
},
{
"Name": 'Garlic',
"Color": 'White',
"ObjectId": '002'
},
}
Here my expected result image :
Accordion-List
I've found the solution, but i'm not sure my method is the best way.
Here is my method :
// GET DATA API
let getObjectApi = this.dataProvider.getObjectUrl();
new Promise(resolve => {
getObjectApi.subscribe(data => {
resolve(data);
this.apiObjectData = data;
// LOOPING OBJECT DATA
for (let i = 0; i < this.apiObjectData.length; i++) {
const objItem = data[i];
// GET OBJECT ITEM BY ObjectId
let getObjectItem = this.getObjectItemByObjectId('ObjectId', objItem['ObjectId']);
// PUSH THE DATA
this.apiDataResult.push({
'dataObject': objItem,
'dataObjectItem' : getObjectItem
});
}
}, err => {
console.log(err);
});
});
And here this.getObjectItemByObjectId() method :
getObjectItemByObjectId(column, value) {
let result:any = [];
let dataApi: any = [];
let getObjectItemApi = this.dataProvider.getObjectItemUrl();
new Promise(resolve => {
getObjectItemApi.subscribe(data => {
resolve(data);
dataApi = data;
for (let i = 0; i < dataApi.length; i++) {
const element = dataApi[i];
if (element[column] == value) {
result.push(element);
}
}
}, err => {
console.log(err);
});
});
return result;
}
And the result is something like this :
{
{
"dataObject": {
"ObjectId": '001',
"ObjectName": 'Fruits'
},
"dataObjectItem": {
{
"Name": 'Apple',
"Color": 'Red',
"ObjectId": '001'
},
{
"Name": 'Banana',
"Color": 'Yellow',
"ObjectId": '001'
}
}
},
{
"dataObject": {
"ObjectId": '002',
"ObjectName": 'Vegetables'
},
"dataObjectItem": {
{
"Name": 'Eggplant',
"Color": 'Purple',
"ObjectId": '002'
},
{
"Name": 'Spinach',
"Color": 'Green',
"ObjectId": '002'
},
{
"Name": 'Garlic',
"Color": 'White',
"ObjectId": '002'
}
}
}
}
That's all!
If there is a better way than my method, please let me know! And sorry if something is goes wrong. Thank you in advance !!

Merge the two different JSON using node JS

I have two requests that return their data as JSON using NodeJS Seriate.
The first response is:
{
"status": true,
"message": "Data Found",
"data": [
{
"statusCode": 200,
"body": {
"expand": "renderedFields,names,schem,operations,editmeta,changelog,versionedRepresentations",
"id": "64672",
"self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
"key": "CKS-2016",
"fields": {
"parent": {
"id": "64670",
"key": "CKS-2014"
}
}
}
}
]
}
The second response is:
{
"statusCode": 200,
"body": {
"errors": [],
"detail": [
{
"repositories": [
{
"name": "registry",
"avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
"avatarDescription": "services"
}
]
}
]
}
}
I want to merge the two responses, that would have the following structure:
{
"status": true,
"message": "Data Found",
"data": [
{
"statusCode": 200,
"body": {
"expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
"id": "64672",
"self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
"key": "CKS-2016",
"fields": {
"parent": {
"id": "64670",
"key": "CKS-2014",
"detail": [
{
"repositories": [
{
"name": "registry",
"avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
"avatarDescription": "services"
}
]
}
]
}
}
}
}
]
}
I searched and found several methods of joining or extending two JSON objects but nothing similar to that.
How can I achieve this?
My Actual Code is,
exports.getIssues = function(req, res) {
console.log(filename + '>>get Issues>>');
var response = {
status : Boolean,
message : String,
data : String
};
var request = require('request');
var username = const.username ;
var password = const.password ;
var options = {
url : 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
auth : {
username : username,
password : password
}
};
request( options, function(error, obj) {
if (error) {
response.message = appmsg.DATA_NT_FOUND;
response.status = false;
response.data = obj;
res.send(response);
} else {
response.message = appmsg.DATA_FOUND;
response.status = true;
response.data = JSON.parse(obj.body);
//res.send(response);
var issueKey = response.data.issues;
// var keyData = issueKey[0].key;
// console.log(response.data.issues);
// console.log(keyData);
var output = [];
for(var i = 0; i < issueKey.length; i++) {
var issue = issueKey[i].key;
//var key = [];
//key.push(issue);
console.log(issue);
var respon = {
status : Boolean,
message : String,
data : String
};
var request = require('request'),
username = const.username ,
password = const.username ,
url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
//console.log(url);
request({url : url,headers : {"Authorization" : auth}}, function(err, object){
if (object) {
var info = object;
output.push(info); // this is not working as ouput is undefined at this point
//var pout = JSON.parse(output);
//console.log(info);
console.log("==============================================================================");
//console.log(output);
console.log("******************************************************************************");
if(issueKey.length === output.length){
respon.message = appmsg.DATA_FOUND;
respon.status = true;
respon.data = output;
//console.log(output);
//res.send(respon);
var id = issueKey[0].id;
console.log(id);
var commitout = [];
for(var i = 0; i < issueKey.length; i++) {
var commits = issueKey[i].id;
console.log(commits);
var request = require('request'),
username = const.username ,
password = const.password ,
url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
//console.log(url);
var test = [];
request({url : url,headers : {"Authorization" : auth}}, function(err, obj1){
if (obj1) {
var info1 = obj1.body;
commitout.push(info1);
if(issueKey.length === commitout.length){
respon.message = appmsg.DATA_FOUND;
respon.status = true;
respon.data = commitout;
// console.log(commitout);
//var test = merge(output, commitout);
var text = output.body;
var resultdone = output;
resultdone.data = resultdone + commitout.body;
console.log(resultdone.data);
res.send(resultdone.data);
}
}
});
}
}
}
});
}
}
});
};
How can i merge the two arrays? in one response. That is my question..
Never mainpulate the string of JSON directly. Parse it first.
const firstRes = JSON.parse(firstResJson);
const secondRes = JSON.prase(secondResJson);
Now, it's a bit unclear what you want to do, and why you want to do it, but try this:
firstRes.data.body.fields.parent.detail = secondRes.body.detail;
Then, you'll find your combined data in firstRes. To get it back to JSON:
JSON.stringify(firstRes);
var obj1 = {
"status": true,
"message": "Data Found",
"data": [
{
"statusCode": 200,
"body": {
"expand": "renderedFields,names,schem,operations,editmeta,changelog,versionedRepresentations",
"id": "64672",
"self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
"key": "CKS-2016",
"fields": {
"parent": {
"id": "64670",
"key": "CKS-2014"
}
}
}
}
]};
var obj2 = {
"statusCode": 200,
"body": {
"errors": [],
"detail": [
{
"repositories": [
{
"name": "registry",
"avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
"avatarDescription": "services"
}
]
}
]}
}
obj1.data.forEach(function(item, index){
item.body.fields.parent.detail = r.body.detail[index];
});
console.log(obj1);
var result1 =
{
"status": true,
"message": "Data Found",
"data": [
{
"statusCode": 200,
"body": {
"expand": "renderedFields,names,schem,operations,editmeta,changelog,versionedRepresentations",
"id": "64672",
"self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
"key": "CKS-2016",
"fields": {
"parent": {
"id": "64670",
"key": "CKS-2014"
}
}
}
}
]
}
var text = result1.data[0].body;
var result2 =
{
"statusCode": 200,
"body": {
"errors": [],
"detail": [
{
"repositories": [
{
"name": "registry",
"avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
"avatarDescription": "services"
}
]
}
]
}
};
var resultdone = result1;
resultdone.data[0].body.fields.parent= result2.body.detail;

How to Read Json in jquery

In below Example, how to access Required value of "DistributorInformation".
using Jquery.
{
"Customization": {
"DistributorInformation": {
"Required": "true"
},
"PostRegistrationData": {
"Required": "false"
}
}
}
var o = {
"Customization": {
"DistributorInformation": {
"Required": "true"
},
"PostRegistrationData": {
"Required": "false"
}
}
}
alert( o.Customization.DistributorInformation.Required);
You can use jQuery.parseJSON() function :
var obj = jQuery.parseJSON( '{
"Customization":{
"DistributorInformation":{"Required":"true"},
"PostRegistrationData":{"Required":"false"}
}}' );
alert(obj.Customization.DistributorInformation.Required);
You can do like so:
// if data is an object
var data = {
"Customization": {
"DistributorInformation": {
"Required": "true"
},
"PostRegistrationData": {
"Required": "false"
}
}
};
Or:
// if data is a string
var data = '{"Customization": {"DistributorInformation": {"Required": "true"},"PostRegistrationData": {"Required": "false"}}}';
data = $.parseJSON(data);
Then:
var required = data.Customization.DistributorInformation.Required;
console.log(required); // outputs "true"
You should be careful about using "true" or "false" since these values are strings and not boolean:
console.log(data.Customization.PostRegistrationData.Required == false)
will output false, so you should check like:
console.log(data.Customization.PostRegistrationData.Required == "false")