Question

I want to display a formatted JSON string in an NSTextView. If I set it directly it will display as continues string, but I need it as formatted like

{    
    "0":"N",
    "J":5    
}

Is there any inbuilt method or 3rd party opensource library to format json?

Was it helpful?

Solution

A lot of JSON parsing frameworks have the option of pretty printing.

For instance SBJsonWriter. It has a humanReadable property.

If set to YES, generates human-readable JSON with linebreaks after each array value and dictionary key/value pair, indented two spaces per nesting level.

If you just want the indentation logic you can dig in and just use that part and strip your project of unnecessary SBJson files.

EDIT:

From OS X 10.7, NSJSONSerialization is available natively in Cocoa.

You can pass the NSJSONWritingPrettyPrinted as an option to +dataWithJSONObject:options:error: class method of NSJSONSerialization to achieve what you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top