Skip to content

Conversation

EricRabil
Copy link

I'm writing an extension that allows JSON output for interaction with other scripts – it required me to open up access to the columns property. I thought I'd send it upstream for those in a similar boat.

I don't think write access is appropriate, as that is what the addRow/addRows functions are for.

@EricRabil
Copy link
Author

EricRabil commented Jan 6, 2021

Probably not perfect, but here's the extension I whipped up:

private extension Array where Element == TextTableColumn {
    var serializedView: NSMutableArray {
        let rows = map {
            $0.values.count
        }.sorted().last ?? 0
        
        print(rows)
        
        let array = NSMutableArray.init(capacity: rows)
        
        for _ in 1 ... rows {
            array.add(NSMutableDictionary())
        }
        
        forEach { column in
            column.values.indices.forEach { index in
                let value = column.values[index]
                
                let dict = array[index] as! NSMutableDictionary
                
                dict.setValue(value, forKey: column.header)
                
                array[index] = dict
            }
        }
        
        return array
    }
}

extension TextTable {
    var json: String {
        let dict = NSMutableDictionary()
        
        let items = columns.serializedView
        
        dict.setValue(items, forKey: "items")
        
        return String(data: try! JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted), encoding: .utf8)!
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant