Swift 사전을 콘솔에 예쁘게 인쇄하는 방법이 있습니까?
NSDictionary *dictionary = @{@"A" : @"alfa",
@"B" : @"bravo",
@"C" : @"charlie",
@"D" : @"delta",
@"E" : @"echo",
@"F" : @"foxtrot"};
NSLog(@"%@", dictionary.description);
콘솔에 다음을 인쇄합니다.
{
A = alfa;
B = bravo;
C = charlie;
D = delta;
E = echo;
F = foxtrot;
}
let dictionary: [String : String] = ["A" : "alfa",
"B" : "bravo",
"C" : "charlie",
"D" : "delta",
"E" : "echo",
"F" : "foxtrot"];
print(dictionary)
콘솔에 다음을 인쇄합니다.
["B": "bravo", "A": "alfa", "F": "foxtrot", "C": "charlie", "D": "delta", "E": "echo"]
Swift에서 각 키-값 쌍이 새 줄을 차지하는 예쁜 인쇄 사전으로 가져 오는 방법이 있습니까?
예를 들어 목표가 사전을 검사하는 경우 dump를 사용할 수 있습니다 . dump
Swift의 표준 라이브러리의 일부입니다.
용법:
let dictionary: [String : String] = ["A" : "alfa",
"B" : "bravo",
"C" : "charlie",
"D" : "delta",
"E" : "echo",
"F" : "foxtrot"]
dump(dictionary)
산출:
dump
반사 (미러링)를 통해 개체의 내용을 인쇄합니다.
어레이 상세보기 :
let names = ["Joe", "Jane", "Jim", "Joyce"]
dump(names)
인쇄물:
▿ 4 가지 요소
-[0] : Joe-
[1] : Jane-
[2] : Jim-
[3] : Joyce
사전의 경우 :
let attributes = ["foo": 10, "bar": 33, "baz": 42]
dump(attributes)
인쇄물:
▿ 키 / 값 쌍 3 개
▿ [0] : (2 개 요소)
- .0 : bar
-.1 : 33
▿ [1] : (2 개 요소)
-.0 : baz
-.1 : 42
▿ [2] : ( 2 요소)
-.0 : foo
-.1 : 10
dump
로 선언됩니다 dump(_:name:indent:maxDepth:maxItems:)
.
첫 번째 매개 변수에는 레이블이 없습니다.
name
검사중인 객체의 레이블을 설정하는 것과 같은 다른 매개 변수를 사용할 수 있습니다 .
dump(attributes, name: "mirroring")
인쇄물:
▿ 미러링 : 3 개의 키 / 값 쌍
▿ [0] : (2 개 요소)
- .0 : bar
-.1 : 33
▿ [1] : (2 개 요소)
-.0 : baz
-.1 : 42
▿ [2] : (2 요소)
-.0 : foo
-.1 : 10
를 사용하여 특정 수의 항목 만 인쇄 maxItems:
하고를 사용하여 특정 깊이까지 개체를 구문 분석 maxDepth:
하고를 사용하여 인쇄 된 개체의 들여 쓰기를 변경 하도록 선택할 수도 있습니다 indent:
.
사전을 'AnyObject'로 캐스팅하는 것이 저에게 가장 간단한 해결책이었습니다.
let dictionary = ["a":"b",
"c":"d",
"e":"f"]
print("This is the console output: \(dictionary as AnyObject)")
이것은 덤프 옵션보다 읽기 쉽지만 총 키-값 수가 제공되지는 않습니다.
PO 솔루션
콘솔 에서 이스케이프 시퀀스가없는 JSON으로 Dictionary를보고 싶은 분들을 위해 여기에 간단한 방법이 있습니다.
(lldb)p print(String(data: try! JSONSerialization.data(withJSONObject: object, options: .prettyPrinted), encoding: .utf8 )!)
함수형 프로그래밍을 사용하는 또 다른 방법
dictionary.forEach { print("\($0): \($1)") }
산출
B: bravo
A: alfa
F: foxtrot
C: charlie
D: delta
E: echo
디버그 목적으로 만 Array 또는 Dictionary를 예쁜 인쇄 된 json으로 변환합니다.
public extension Collection {
/// Convert self to JSON String.
/// - Returns: Returns the JSON as String or empty string if error while parsing.
func json() -> String {
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted])
guard let jsonString = String(data: jsonData, encoding: String.Encoding.utf8) else {
print("Can't create string with data.")
return "{}"
}
return jsonString
} catch let parseError {
print("json serialization error: \(parseError)")
return "{}"
}
}
}
그때:
print("\nHTTP request: \(URL)\nParams: \(params.json())\n")
콘솔 결과 :
HTTP request: https://example.com/get-data
Params: {
"lon" : 10.8663676,
"radius" : 111131.8046875,
"lat" : 23.8063882,
"index_start" : 0,
"uid" : 1
}
JSON 유효성 검사기에 결과를 전달할 때 결과가 유효하지 않기 때문에 여기에 제공된 많은 답변을 고려하지 않을 것입니다 (종종 ':'이 아닌 '='를 포함하는 코드로 인해).
내가 찾은 가장 쉬운 방법은 예쁜 인쇄 된 쓰기 옵션을 사용하여 JSON 객체를 데이터로 변환 한 다음 결과 데이터를 사용하여 문자열을 인쇄하는 것입니다.
다음은 예입니다.
let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
if let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
}
결과:
{
"jsonData": [
"Some String"
],
"moreJSONData": "Another String",
"evenMoreJSONData": {
"A final String": "awd"
}
}
편집 : OP가 JSON을 요청하지 않았다고 지적되었지만 데이터를 콘솔에 인쇄하거나 덤프하는 것을 권장하는 답변은 (있는 경우) 매우 적은 형식을 제공하므로 예쁜 인쇄가 아닙니다.
나는 OP가 JSON을 요구하지 않음에도 불구하고 xcode / swift에 의해 콘솔에 튀어 나온 끔찍한 형식보다 데이터에 대해 훨씬 더 읽기 쉬운 형식이므로 실행 가능한 대답이라고 생각합니다.
for 루프를 사용하고 각 반복을 인쇄 할 수 있습니다.
for (key,value) in dictionary {
print("\(key) = \(value)")
}
확장 응용 프로그램 :
extension Dictionary where Key: CustomDebugStringConvertible, Value:CustomDebugStringConvertible {
var prettyprint : String {
for (key,value) in self {
print("\(key) = \(value)")
}
return self.description
}
}
대체 응용 프로그램 :
extension Dictionary where Key: CustomDebugStringConvertible, Value:CustomDebugStringConvertible {
func prettyPrint(){
for (key,value) in self {
print("\(key) = \(value)")
}
}
}
용법:
dictionary.prettyprint //var prettyprint
dictionary.prettyPrint //func prettyPrint
출력 (Xcode 8 베타 2 플레이 그라운드에서 테스트 됨) :
A = alfa
B = bravo
C = charlie
D = delta
E = echo
F = foxtrot
들어 스위프트 3 (&로 화려한 답변을 구축 @Jalakoo ), 다음 수 있도록 Dictionary
확장 :
extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {
var prettyPrint: String {
return String(describing: self as AnyObject)
}
}
다음의 사전 인쇄 어떤 계층 구조를 A의 꽤 (보다 나은 방법 dump()
이 사용) :
print(dictionary!.prettyPrint)
Swift Dictionary를 json으로 변환하는 방법은 가장 간단합니다. 나는 일반적으로 Swift 사전을 인쇄하기 위해 pjson 명령 이있는 Facebook의 끌 을 사용 합니다. 예 :
(lldb) pjson dict as NSDictionary
이것은 사전을 예쁘게 인쇄해야합니다. 이것은 이미 제안 된 작업을 수행하는 훨씬 더 깨끗한 방법입니다. 추신 : Objective-C 런타임은 Swift 사전을 이해하지 못하기 때문에 지금은 dict를 NSDictionary로 캐스팅해야합니다. 나는 이미 그 제한을 없애기 위해 끌에 대한 PR을 올렸습니다.
세부
- Xcode 10.2.1 (10E1001), Swift 5
해결책
extension Dictionary {
func format(options: JSONSerialization.WritingOptions) -> Any? {
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: options)
return try JSONSerialization.jsonObject(with: jsonData, options: [.allowFragments])
} catch {
print(error.localizedDescription)
return nil
}
}
}
용법
let dictionary: [String : Any] = [
"id": 0,
"bool": true,
"int_array": [1,3,5],
"dict_array": [
["id": 1, "text": "text1"],
["id": 1, "text": "text2"]
]
]
print("Regualr print:\n\(dictionary)\n")
guard let formatedDictionary = dictionary.format(options: [.prettyPrinted, .sortedKeys]) else { return }
print("Pretty printed:\n\(formatedDictionary)\n")
결과
어때 :
import Foundation
extension Dictionary {
var myDesc: String {
get {
var v = ""
for (key, value) in self {
v += ("\(key) = \(value)\n")
}
return v
}
}
}
// Then, later, for any dictionary:
print(dictionary.myDesc)
extension String {
var conslePrintString: String {
guard let data = "\""
.appending(
replacingOccurrences(of: "\\u", with: "\\U")
.replacingOccurrences(of: "\"", with: "\\\"")
)
.appending("\"")
.data(using: .utf8) else {
return self
}
guard let propertyList = try? PropertyListSerialization.propertyList(from: data,
options: [],
format: nil) else {
return self
}
guard let string = propertyList as? String else {
return self
}
return string.replacingOccurrences(of: "\\r\\n", with: "\n")
}
}
let code in extension String and it works fine
let string = "\(jsonDictionary)".conslePrintString
'program tip' 카테고리의 다른 글
C #에서 foreach 루프 종료 (0) | 2020.10.25 |
---|---|
0과 1 사이의 신속한 임의 부동 (0) | 2020.10.25 |
Android 열 '_id'가 존재하지 않습니까? (0) | 2020.10.25 |
jQuery없이 node.js에서 JSON 결합 또는 병합 (0) | 2020.10.25 |
$ date + 1 년? (0) | 2020.10.25 |