Skip to content

Instantly share code, notes, and snippets.

@moduscreate
Created April 13, 2015 20:55
Show Gist options
  • Save moduscreate/cf79d1bc29da6603333d to your computer and use it in GitHub Desktop.
Save moduscreate/cf79d1bc29da6603333d to your computer and use it in GitHub Desktop.
//
// main.m
// json_formatter
//
// Created by Jesus Garcia on 3/29/15.
// Copyright (c) 2015 Jesus Garcia. All rights reserved.
//
#import <Foundation/Foundation.h>
void doWork(int argc, const char * argv[]) {
NSFileManager *fileMgr = [[NSFileManager alloc] init];
NSString *srcFilePath = [[NSString alloc] initWithUTF8String:argv[1]];
NSString *cwd = [[fileMgr currentDirectoryPath] stringByAppendingString:@"/"];
srcFilePath = [cwd stringByAppendingString:srcFilePath];
NSString *srcConent = [NSString stringWithContentsOfFile:srcFilePath encoding:NSUTF8StringEncoding error:nil];
NSData *srcJsonData = [srcConent dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *srcDict = [NSJSONSerialization JSONObjectWithData:srcJsonData
options:NSJSONReadingMutableContainers
error:nil];
// sort the keys
NSArray *sortedKeys = [[srcDict allKeys] sortedArrayUsingSelector: @selector(compare:)];
NSMutableDictionary *sortedValues = [NSMutableDictionary dictionary];
// Loop through sorted keys adding them to the nsmutable dict.
for (NSString *key in sortedKeys) {
[sortedValues setValue:[srcDict objectForKey:key] forKey:key];
}
NSData *outData = [NSJSONSerialization
dataWithJSONObject:sortedValues
options:NSJSONWritingPrettyPrinted
error:nil
];
NSString *outDataAsString = [[NSString alloc] initWithData:outData encoding:NSUTF8StringEncoding];
NSString *destFilePath = [[NSString alloc] initWithUTF8String:argv[2]];
destFilePath = [cwd stringByAppendingString:destFilePath];
[outDataAsString writeToFile:destFilePath atomically:true encoding:NSUTF8StringEncoding error:nil];
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
if (argc < 3) {
printf("ERROR: Must require source and target files, fool!\n");
exit(1);
}
doWork(argc, argv);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment