-1

I am looking to parse some JSON into a dictionary but need to preserve order for one particular part of the dictionary.

I know that I can parse the entire JSON file into an ordered dictionary (ex. Can I get JSON to load into an OrderedDict?) but this is not quite what I'm looking for.

{
    "foo": "bar",
    "columns":
    {
        "col_1": [],
        "col_2": []
    }
}

In this example, I would want to parse the entire file in as a dictionary with the "columns" portion being an OrderedDict. Is it possible to get that granular with the JSON parsing tools while guaranteeing that order is preserved throughout? Thank you!

J. K.
  • 41
  • 7
  • 1
    not sure why you don't want the complete result to be an OrderedDict, but if you don't care about efficiency too much, you could always do the following: `dict(json.loads("YOUR INPUT", object_pairs_hook=OrderedDict))` :-) – Bart Van Loon Jun 06 '19 at 15:35
  • @BartVanLoon Thank you! I'm potentially fine with the entire thing being an `OrderedDict`. Would that guarantee the order of `columns` or would it end up being an `OrderedDict` with an orderless dictionary `columns` as a child? If that makes sense. – J. K. Jun 06 '19 at 15:39
  • 1
    no, it will be an OrderedDict all the way down – Bart Van Loon Jun 06 '19 at 15:44
  • @BartVanLoon thanks for all the help! Great information. I am a little new to Python so I appreciate your patience :) – J. K. Jun 06 '19 at 15:46

1 Answers1

0

From the comments meanwhile, I gathered that a complete, nested OrderedDict is fine as well, but this could be a solution too, if you don't mind using some knowledge about the names of the columns:

import json
from collections import OrderedDict

def hook(partialjson):
    if "col_1" in partialjson:
        return OrderedDict(partialjson)
    return dict(partialjson)

result = json.loads("YOUR JSON STRING", object_hook=hook)

Hope this helps!

Bart Van Loon
  • 1,430
  • 8
  • 18