Xbasic

json_flatten_single Function

Syntax

C jsonOut = json_flatten_single(C jsonIn [, N depth])

Arguments

jsonInCharacter

The JSON containing nested arrays.

depthNumeric

The maximum number of rows from a nested child array to use. Defaults to -1 (all rows in the child array).

Returns

jsonOutCharacter

Returns the flattened JSON.

Description

Takes a JSON string with nested arrays and flattens the JSON so that there are no nested arrays. Data from the nested arrays are represented represented in the parent data as a set of repeating fields.

Discussion

This function will only operate on one level of nested arrays. For example if a row in a nested array has another nested array, this array will be ignored.

Notice in the example below that data from the nested arrays is represented in the parent record as a set of repeating fields. For example, Children_1_Name, Children_2_Name, etc.

Example

dim json as c 
json = <<%str%
[
    {"name": "John", "Lastname" : "Smith", "City" : "Boston", "State" : "MA", "Children": [
            {"Name" : "Callie", "Age" : 5},
            {"Name" : "Griffin", "Age" :3},
            {"Name" : "Luke", "Age" : 1}
        ]
    }, 
    {"name": "Henry", "Lastname" : "Rhodes", "City" : "New York", "State" : "NY", "Children": [
            {"Name" : "Howard", "Age" : 15},
            {"Name" : "Robert", "Age" : 11}
        ]
    }, 
    {"name": "Allison", "Lastname" : "Berman", "City" : "Los Angeles", "State" : "CA", "Children": [
            {"Name" : "Jeff", "Age" : 35},
            {"Name" : "Roxanne", "Age" :33},
            {"Name" : "Claudia", "Age" : 31},
            {"Name" : "Denzel", "Age" : 11}
        ]
    }
]
%str%
dim json2 as c
json2 = json_flatten_single(json)
?json2

= [
{"name": "John","Lastname": "Smith","City": "Boston","State": "MA","Children_1_Name": "Callie","Children_1_Age": 5,"Children_2_Name": "Griffin","Children_2_Age": 3,"Children_3_Name": "Luke","Children_3_Age": 1},
{"name": "Henry","Lastname": "Rhodes","City": "New York","State": "NY","Children_1_Name": "Howard","Children_1_Age": 15,"Children_2_Name": "Robert","Children_2_Age": 11},
{"name": "Allison","Lastname": "Berman","City": "Los Angeles","State": "CA","Children_1_Name": "Jeff","Children_1_Age": 35,"Children_2_Name": "Roxanne","Children_2_Age": 33,"Children_3_Name": "Claudia","Children_3_Age": 31,"Children_4_Name": "Denzel","Children_4_Age": 11}
]