Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way of sorting a plist (array of dictionaries) by key value?

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.

like image 935
Matt Sephton Avatar asked Nov 30 '22 20:11

Matt Sephton


2 Answers

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];
like image 124
Brian Webster Avatar answered Dec 02 '22 09:12

Brian Webster


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)
like image 32
Kristopher Johnson Avatar answered Dec 02 '22 08:12

Kristopher Johnson