How to get an ordered list of keys from a json file? #14373
Replies: 4 comments 2 replies
-
I proposed this by default in #6135 |
Beta Was this translation helpful? Give feedback.
-
I think json.loads() is the problem since it jumbles everything up. So only option is to roll your own JSON parser that does it in order?
|
Beta Was this translation helpful? Give feedback.
-
Would your implementation work with a json array {[]} of things ? |
Beta Was this translation helpful? Give feedback.
-
I suspect not! Good to be clear about its limitations. Mine is a basic (partial, spec-breaking?) JSON parser that works for what I need. Which is to load up a little Menu from a text file where the order matters. No arrays. Perhaps YAML would a better format for my menu configured bv a text file. However, there's no decent library to help me parse YAML in Micropython, and my attempt to make my own failed (it couldn't do nested submenus). I'm going to stick with "ordered" JSON for my purposes. |
Beta Was this translation helpful? Give feedback.
-
Let’s say I have a json file with the following structure:
{
"list of objects": {
"key 1": {...},
"key 2": {...},
"key 3": {...},
...
},
...
}
What I need is a list of the keys in ‘list of objects’, in exactly the same order as in the json file.
If I load it this way, I get a randomly ordered list:
import ujson as json
json_file = open('json_file.json')
data = json.load(json_file)
list_of_keys = list(data['list of objects'])
Is there any way to get a list of keys in the original order? I’ve tried using
object_pairs_hook=OrderedDict
, but the MicroPython implementation of json/ujson doesn’t seem to implementobject_pairs_hook
.Beta Was this translation helpful? Give feedback.
All reactions