0

I'm trying to serialise a list of dictionaries as json files. Some of the values in the dictionaries are lists which are defined somewhere else. I would like to serialise the name of the list, not the "expanded" list. For example, say I have this:

list1 = ["A", "B", "C"]

dict1 = {
   "key1": "foo",
   "key2": list1
}

serialise_it(dict1)

If I just save the dict normally with the json package, it will contain:

{
   "key1": "foo",
   "key2": ["A", "B", "C"]
}

But I would like the resulting json file to contain:

{
   "key1": "foo",
   "key2": "list1"
}

Any ideas how to achieve this?

Thanks

EDIT: For clarification, I have a few list of lists each of hundreds of dictionaries which I am trying to convert into files. I'd rather not go through these manually adding quotation marks if there is a way to do it in code.

kazimpal
  • 270
  • 3
  • 13
  • 2
    why not pass list1 as a string 'list1' – Ade_1 Jun 07 '21 at 12:43
  • Check out this StackOverflow answer. It shows how to get the variable names as a string. https://stackoverflow.com/a/58451182/5534234 – David K. Jun 07 '21 at 12:46
  • 1
    If the variable names are important, you should be using a `dict` in the first place. Variable names are *code*, not data. – chepner Jun 07 '21 at 12:48
  • If your intent is to reconstruct your *variables* in another process, I would not do that either. *Data* is transferred between programs, not parts of the code. – chepner Jun 07 '21 at 12:50
  • @chepner I agree with what you're saying. I have inherited some some bad code that I'm trying to turn into better code. Part of this process involves transforming these dictionaries into config files, and it makes sense for the config files to contain the name "list1" (as in the example above) not the list itself. – kazimpal Jun 07 '21 at 12:58
  • Pure JSON has no notion of references, which is what you are trying to encode. `dict1` itself has no notion of its `key2` value coming from a variable named `list1`. Think about it: you have a JSON file containing`{ "key1": "foo", "key2": "list1" }`; what are you going to *do* with that file? When you read this file later, what does the value `"list1"` tell you? Do you have another object like `{ ..., "list1": ["A", "B", "C"], ...}` stored elsewhere that you'll use to reconstruct the original variables later? (And reconstructing variable names is another issue entirely.) – chepner Jun 07 '21 at 13:03
  • I understand json doesn't have references. I already have code that can compose dictionaries in a way that enables modular config files which can reference/inherit/etc from each other, so yes `{ ..., "list1": ["A", "B", "C"], ...}` will probably be in a dictionary or its own config file somewhere, but that isn't what I'm asking about. I'm just asking about one stage of a larger refactor. – kazimpal Jun 07 '21 at 13:09

0 Answers0