What is the best way to exclude fields when unmarshalling JSON in a Golang application?

In my program, I utilize a JSON file to set up the arguments and also use the flag package to configure the same arguments.

Whenever an argument is parsed by both the JSON file and the flag at the same time, I prefer to use the argument parsed through the flag.

The issue arises when the JSON file path is also parsed through the flag. The JSON path can be retrieved after calling `flag.parse()`, but since the arguments are already parsed, unmarshaling the JSON will overwrite the arguments from flag parsing.

Example JSON:

{
    "opt1": 1,
    "opt2": "hello"
}

Example code:

var Config = struct {
    Opt1 int    `json:"opt1"`
    Opt2 string `json:"opt2"`
}{
    Opt1: 0,
    Opt2: "none",
}

func main() {

    // Parse config file path
    var configFile string
    flag.StringVar(&configFile, "config", "", "config file path")

    // Parse options
    flag.IntVar(&Config.Opt1, "opt1", Config.Opt1, "")
    flag.StringVar(&Config.Opt2, "opt2", Config.Opt2, "")

    // Parse flags
    flag.Parse()

    // Load config options from config.json file
    if configFile != "" {
        if data, err := ioutil.ReadFile(configFile); err != nil {
            fmt.Printf("read config file error: %v\n", err)
        } else if err = json.Unmarshal(data, &Config); err != nil {
            fmt.Printf("parse config file error: %v\n", err)
        }
    }

    fmt.Printf("%+v", Config)
}

Program example output:
./foo.exe -opt2 world
out: {Opt1:0 Opt2:world}

./foo.exe -config config.json
out: {Opt1:1 Opt2:hello}

./foo.exe -config config.json -opt2 world

real out: {Opt1:1 Opt2:hello}
desired out: {Opt1:1 Opt2:world}

Answer №1

If you are looking for a simple solution, consider starting by parsing the JSON configuration file before moving on to parsing CLI arguments.

However, one issue you may encounter is that the JSON config file itself is considered a CLI argument.

To address this, a straightforward approach would be to re-enable flag.Parse() after parsing the config file:

// retrieve configuration options from the config.json file
if configFile != "" {
    if data, err := ioutil.ReadFile(configFile); err != nil {
        fmt.Printf("error reading config file: %v\n", err)
    } else if err = json.Unmarshal(data, &Config); err != nil {
        fmt.Printf("error parsing config file: %v\n", err)
    }

    // parse flags again to prioritize them
    flag.Parse()
}

The second call to flag.Parse() will take precedence and overwrite any data from the JSON file.

By incorporating this addition, when running

./foo.exe -config config.json -opt2 world

You will achieve the desired output:

{Opt1:1 Opt2:world}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I convert a text file to JSON format using Python?

My log file has the following format: Nov 28 06:26:45 server-01 dhcpd: DHCPDISCOVER from cc:d3:e2:7a:af:40 via 10.39.192.1 Nov 28 06:26:45 server-01 dhcpd: DHCPOFFER on 10.39.255.253 to cc:d3:e2:7a:af:40 via 10.39.192.1 I am in the process of converting ...

Tips for presenting Nested JSON information?

I am having trouble figuring out the correct syntax to display DietName from Data{}, PartnerName from PartnerData[], and DayName from DayList[]. These data are inside another ArrayList, and I need help displaying them. { "Status": "1", "Message": " ...

Managing a substantial JSON object on an Android device: Tips and Tricks

Currently, I am working on creating an Android application that interacts with an ASP.NET WebService. The Webservice sends a JSON object to the app, which then parses the data and displays it on the screen. However, I have encountered an issue where the ...

The optimal organization of factories in AngularJS

I have a dilemma with my AngularJS single page application where I find myself calling the JSON file twice in each method $http.get('content/calendar.json').success(function(data) {.... Is there a more efficient way to make this call just once, ...

What is the best way to transform a JSON object from a remote source into an Array using JavaScript?

Attempting to transform the JSON object retrieved from my Icecast server into an array for easy access to current listener statistics to display in HTML. Below is the JavaScript code being used: const endpoint = 'http://stream.8k.nz:8000/status-json ...

Substitute data in json

I'm currently working on displaying data from a JSON file and I need to replace certain values for translation purposes. Here is the code snippet I am dealing with: <li ng-repeat="childrens in data.children track by $index"> <a& ...

Understanding the basics of reading a JSON object in TypeScript

Displayed below is a basic JSON structure: { "carousel": [], "column-headers": [{ "header": "Heading", "text": "Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id el ...

How to retrieve data from a JSON.NET array using C#

I'm having trouble accessing all the JSON data that was deserialized using json.net. The data appears to be null when I try to output it in the console. How can I access it? Account.cs public class Account { public string Email { get; set; } public ...

Are you familiar with manipulating the JSON data array retrieved from an Ajax response?

Is it possible to handle a response from AJAX request in PHP? I'm not very familiar with JavaScript, so I'm struggling with this one. This is what I have managed to put together: var base_url = 'http://dev.local/westview/public'; $(& ...

Rendering nested data structures in Django using a tree view

My backend server sends me a JSON response structured as follows: { "compiler": { "type": "GCC", "version": "5.4" }, "cpu": { "architecture": "x86_64", "count": 4 } } I am looking to represent this response ...

Having trouble with the Google Places API integration using Python

Hey there! I'm currently experimenting with the Google Places API in a rather unique way - trying to fetch a list of all McDonald's locations in Germany. I know, it's a bit unusual! Below is the code I've put together for this task (the ...

Decoding JSON with YAJL

I am currently working on parsing the JSON data provided below using YAJL. The issue I am encountering is that the number of arrays (such as KEY and CUSTOMER) returned for each field in the response is not fixed. I am trying to find a way to avoid defining ...

Encountering an error when attempting to parse a JSON Object in Java from an AJAX call

** Latest Code Update ** My JavaScript and Ajax Implementation: $(function() { $("#create_obd").bind("click", function(event) { var soNumber = []; $('#sales_order_lineItems input[type=checkbox]:checked').eac ...

What is the best way to assign multiple values to certain elements within an array?

I have an array that looks like this: items = { item1: 10, item2: 5, item3: 7, item4: 3, }; I am looking to include additional details in this array, for example: items = { item1: 10 {available: true}, ...

Retrieve the JSON encoded output from the Controller and pass it to the View

I am trying to convert a json encoded result from ManagementController.php, specifically the statisticAction, into Highchart syntax within the view file (stat.phtml) in my Phalcon project. Originally, in the stat.phtml file, I had the following: ...

The Rails JSON API is returning only the `created_at` and `updated_at`

I've recently set up a json API to retrieve bike data. The API is functional and returns json successfully, but I'm encountering an issue where it only includes the 'created_at' and 'updated_at' fields. This is what exists in ...

Transmit information via ajax and receive responses in json format

Looking to send a string and receive JSON format in return. The current method is functional but lacks the ability to return JSON code. $.ajax({ url: "getFeed.php", type: "post", data: myString }); Attempts to retrieve JSON string result in ...

Utilize vis.js to visualize networkx data in a visually interactive manner

Currently, I am utilizing the networkx Python library to construct a directed graph containing nearly 2k nodes. My goal is to visually represent this graph using the vis.js library. While I am able to export the graph as Json data, I am struggling to crea ...

unable to display friends' names in chat

Can someone assist me with an issue I'm facing in my chat application? Whenever I try to display a friend's name on the chat, the app crashes. If I remove the part where the friend's name is displayed, the messages show up fine. However, as ...

Unexpected JSON response from jQuery AJAX call

Trying to make a request for a json file using AJAX (jQuery) from NBA.com Initially tried obtaining the json file but encountered a CORS error, so attempted using jsonp instead Resulted in receiving an object filled with functions and methods rather than ...