DEV Community

Cover image for Expand-JsonFile
Antonio Di Motta
Antonio Di Motta

Posted on • Edited on

Expand-JsonFile

Json format is an amazing way to define things, so devs often use it into the code repository to describe entities. Devops also uses json files to configure application or other stuff.

Proliferation of the number of json files and inconsistent data could be a problem, so to avoid them I have created a small powershell script that is able to resolve expressions contained into json file. The expression defines the correlation between different files.

Example:

Into the data folder there are three json files:

  • customers.json (which contains a set of customer)
  • products.json (which contains a set of product)
  • orders.json (which contains a set of order)

The orders.json has two properties (product and customer) which need to be calculated by evaluating a reference expression:

// orders.json
[
    {
        "created":"2022-10-15T09:00:00",
        "product":"[data/products(pid=1).title]",
        "quantity":1,
        "customer":"[data/customers(cid=3).name]",
        "notes":"this is a note"
    },
    {
        "created":"2022-10-15T10:00:00",
        "product":"[data/products(pid=2).title]",
        "quantity":2,
        "customer":"[data/customers(cid=3).name]",
        "notes":"this is a note2"
    }
]
Enter fullscreen mode Exit fullscreen mode

The function Expand-JsonFile evaluates the reference expressions contained in the orders.json file and produce a new file:

import-module -name .\ADMjson.psm1 -Force
Expand-JsonFile -SourceFile data/orders.json -TargetFile data/orders_expanded.json
Enter fullscreen mode Exit fullscreen mode

The result json file contains property values:

// orders_expanded.json
[
    {
        "created": "2022-10-15T09:00:00",
        "product": "xbox",
        "quantity": 1,
        "customer": "Paperino",
        "notes": "this is a note"
    },
    {
        "created": "2022-10-15T10:00:00",
        "product": "playstation",
        "quantity": 2,
        "customer": "Paperino",
        "notes": "this is a note2"
    }
]
Enter fullscreen mode Exit fullscreen mode

The script code is available here

Top comments (0)