Command-line tool for converting PLIST to JSON?
Asked Answered
H

9

79

Is there a command line tool available for converting .plist files to JSON?

If not, what would be the approach for creating one using Objective-C or C on a Mac? For instance, there is JSONKit, for Objective-C. How would one go about opening a .plist file, pass it to JSONKit, and serialize that as JSON?

Helgahelge answered 20/5, 2011 at 0:39 Comment(0)
S
184

If you are on a Mac you can use the plutil tool on the command line (this comes with the developer tools I believe):

plutil -convert json -o Data.json Data.plist

If you want to just overwrite the existing file, you can omit the -o parameter:

plutil -convert json Data.plist
Shrubbery answered 12/6, 2012 at 6:46 Comment(8)
This will overwrite the original plist. To prevent this command from overwriting the original file pass the -o flag. ie plutil -convert json Data.plist -o Data.jsonTeel
One complication with this is that some Plist data types cannot be converted by plutil. The workaround I found was to do some pre-processing on the plist before passing it to plutil. Specific to the plist that I'm working with, I had to replace both <data> and <date> tags with <string>.Helgahelge
I don't know on what Macs this is supposed to work, but on 10.6 it says: Unknown format specifier: jsonNaman
Your second command will convert the original plist file all the same. It should be plutil -convert json -o Data.json Data.plist. That's to say, the original plist file should be at last. @TeelOverdone
use plutil -convert -r json to receive the json in a human-readable formatPlatinize
Pass a hyphen as the output file to print to stdout. plutil -convert json -o - file.jsonSuperimpose
You need to edit your answer and completely remove the 1st command, which destructively modifies the original plist file. It is simply wrong for this purpose.Dashpot
For the life of me, I can't get this command to work, "invalid object in plist for destination format".Felixfeliza
C
6

If you run into issues with "invalid object in plist for destination format", you probably have bytes-like data in the plist, which plutil does not consider serializable to json.

Python has built-in plist support, and we can specify a custom default function to specify what to do when serialization fails (e.g. on bytes). If you don't care about the bytes fields, we can just serialize them as '<not serializable>' with the following python one-liner:

python -c 'import plistlib,sys,json; print(json.dumps(plistlib.loads(sys.stdin.read().encode("utf-8")), default=lambda o:"<not serializable>"))'

This takes the stdin, parses the plist, then dumps it to json. For example, to get current power information for your Mac, you can run:

ioreg -rw0 -c AppleSmartBattery -a | python -c 'import plistlib,sys,json; print(json.dumps(plistlib.loads(sys.stdin.read().encode("utf-8")), default=lambda o:"<not serializable>"))'

and if you wanted to just get the current charging wattage, you could pipe that into jq '.[0].AdapterDetails.Watts'

Conterminous answered 12/7, 2022 at 21:11 Comment(0)
E
5

The following gets the job done—

// convertPlistToJSON.m
#import <Foundation/Foundation.h>
#import "JSONKit.h"

int main(int argc, char *argv[]) {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

  if(argc != 3) { fprintf(stderr, "usage: %s FILE_PLIST FILE_JSON\n", argv[0]); exit(5); }

  NSString *plistFileNameString = [NSString stringWithUTF8String:argv[1]];
  NSString *jsonFileNameString  = [NSString stringWithUTF8String:argv[2]];

  NSError *error = NULL;

  NSData *plistFileData = [NSData dataWithContentsOfFile:plistFileNameString options:0UL error:&error];
  if(plistFileData == NULL) {
    NSLog(@"Unable to read plist file.  Error: %@, info: %@", error, [error userInfo]);
    exit(1);
  }

  id plist = [NSPropertyListSerialization propertyListWithData:plistFileData options:NSPropertyListImmutable format:NULL error:&error];
  if(plist == NULL) {
    NSLog(@"Unable to deserialize property list.  Error: %@, info: %@", error, [error userInfo]);
    exit(1);
  }

  NSData *jsonData = [plist JSONDataWithOptions:JKSerializeOptionPretty error:&error];
  if(jsonData == NULL) {
    NSLog(@"Unable to serialize plist to JSON.  Error: %@, info: %@", error, [error userInfo]);
    exit(1);
  }

  if([jsonData writeToFile:jsonFileNameString options:NSDataWritingAtomic error:&error] == NO) {
    NSLog(@"Unable to write JSON to file.  Error: %@, info: %@", error, [error userInfo]);
    exit(1);
  }

  [pool release]; pool = NULL;
  return(0);
}

It does some reasonable error checking, but it's not bullet proof. Use at your own risk.

You'll need JSONKit to build the tool. Place JSONKit.m and JSONKit.h in the same directory as convertPlistToJSON.m, and then compile with:

shell% gcc -o convertPlistToJSON convertPlistToJSON.m JSONKit.m -framework Foundation

Usage:

shell% convertPlistTOJSON
usage: convertPlistToJSON FILE_PLIST FILE_JSON

shell% convertPlistTOJSON input.plist output.json

Reads in input.plist, and writes the pretty printed JSON to output.json.

Entomb answered 21/5, 2011 at 2:56 Comment(0)
P
4

Using mac utils

Convert plist to json

plutil -convert json -o output.json input.plist

Convert json to plist

plutil -convert xml1 input.json -o output.plist
Prem answered 3/6, 2019 at 15:3 Comment(0)
U
2

The code is fairly simple to do this:

NSArray* array = [[NSArray arrayWithContentsOfFile:[@"~/input.plist" stringByExpandingTildeInPath]]retain];
SBJsonWriter* writer = [[SBJsonWriter alloc] init];
NSString* s = [[writer stringWithObject:array] retain];
[s writeToFile:[@"~/output.json" stringByExpandingTildeInPath] atomically:YES];
[array release];

I never got around to making it accept arguments as I only needed to do 3 files.

Unfaithful answered 20/5, 2011 at 2:36 Comment(0)
P
2

I wrote a tool in python to do this. See here:

http://sourceforge.net/projects/plist2json

Works from command line on os x or linux distros, batch converts a directory. It's short and simple so it should be easy to modify for your own purposes.

Poultryman answered 31/12, 2011 at 20:47 Comment(0)
D
2

There is a native way, to convert plist's to json. It's called NSJSONSerialization.

Here is an example on how to use it, and convert a plist file to a json file:

NSDictionary *plistDict = [NSDictionary dictionaryWithContentsOfFile:@"input.plist"];

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:plistDict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[jsonString writeToFile:@"output.json" atomically:NO encoding:NSUTF8StringEncoding error:&error];
Discriminating answered 30/4, 2014 at 15:27 Comment(0)
L
2

Converts Filename.plist to Filename.json:

plutil -convert json -r -e json Filename.plist

-convert indicates format, -r makes the output more human-readable, -e specifies an extension

Lakeesha answered 30/8, 2020 at 11:41 Comment(0)
S
0

I was annoyed at how kinda complicated converting binary plists to json was, so I created a web, browser-only tool that converts binary plist files to json.

your files are not sent anywhere, it's all done in the browser!

https://gregsadetsky.github.io/i-just-want-to-see-the-plist/

its code is open and can be found here.

Sough answered 19/9, 2023 at 22:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.