Sublime Forum

[Solved] Iterate through keys of `.sublime-settings` file

#1

I have a plugin which uses a .sublime-settings file.
The keys in the file are dynamically created (from path names).

I would like to implement a clear method in order to reset the settings to their defaults - but I can’t seem to iterate over the keys of the file?

Something like:

settings = sublime.load_settings('MyPlugin.sublime-settings')
for key, value in settings.items():
  settings.erase(key)
0 Likes

#2

As far as I’m aware, there is no direct way to iterate over the keys in a settings object.

Since settings files are just JSON, you can get around that by loading the contents of the settings file as JSON, parsing it into a native object, and then iterating the keys on that.

An example of that might be:

settings = sublime.load_settings("MyPlugin.sublime-settings")
files = sublime.find_resources("MyPlugin.sublime-settings")

for file in files:
    try:
        for key in sublime.decode_value(sublime.load_resource(file)):
            settings.erase(key)
    except:
        print("Error Loading settings file")

Although load_settings() ensures that it will find, load and merge all of the sublime-settings files with the name you provide, load_resource() does not. However, the find_resources() call will find all of the different individual files where MyPlugin.sublime-settings exists and return it as a list, so you can simulate that behaviour if you need to.

If you happen to know that you only need to look at a single specific settings file, you could skip that step and just load the single file instead, e.g. Packages/User/MyPlugin.sublime-settings to get the version in the User package.

3 Likes

#3

Thanks for the quick reply! :+1:

That’s a good approach, I think I’ll use that.
I had just resorted to storing the keys in a list in the settings file, but that used unnecessary space. Your method is better - thanks :smile:

0 Likes