I need to reorder a plist (an array of dictonaries) by Key value.
In this example content I'd like to order by the value for the key Name (Matt, Joe):
<dict>
<key>Name</key>
<string>Matt</string>
<key>Details</key>
<string>Me</string>
</dict>
<dict>
<key>Name</key>
<string>Joe</string>
<key>Details</key>
<string>You</string>
</dict>
Is there an easy way? I don't want to do it in code each time the app is run, I just want to do it to the data file.
Any ideas?
Happy to use any tool to get this done: ninja parameters for sort on the command line, a plist editor, text editor or whatever.
This is another coding solution, but it wouldn't be hard to make a basic command line tool that wrapped around it:
NSArray* arrayOfDictionaries; //the array we want to sort
NSSortDescriptor* nameSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES];
NSArray* sortedArray = [arrayOfDictionaries sortedArrayUsingDescriptors:[NSArray arrayWithObject:nameSortDescriptor]];
[nameSortDescriptor release];
I wrote a little Python script that reads from standard input and writes to standard output:
#/usr/bin/env python3
# Save as sortplist.py
import plistlib
import sys
with open(sys.argv[1], 'rb') as f:
plist = plistlib.load(f)
xml_bytes = plistlib.dumps(plist, sort_keys=True)
print(str(xml_bytes, 'utf-8'))
So, just do python3 sortplist.py original.plist >sorted.plist
.
The above works with Python 3.4+. If you need to use an older version of Python, this works with the older plistlib
API:
# sortplist.py
import plistlib
import sys
plist = plistlib.readPlist(sys.stdin)
plistlib.writePlist(plist, sys.stdout)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With