我有json数据来自服务器端。
如果我使用下一个代码,我就不会打印出一个字符串:
if let json = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) {
if let prettyPrintedData = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) {
print(String(bytes: prettyPrintedData, encoding: String.Encoding.utf8) ?? "NIL")
}
}
为了使它打印得漂亮,我使用下一个代码:
$sum
但似乎这不是最好的方式。
那么有人知道如何打印传入的jsonData来打印它吗?
答案 0 :(得分:1)
您所拥有的产品的略美版本:
X_train = np.array([x.tolist() for x in df['board_in'].values])
y_train = df['target']
y_train = np.array([y for y in df['target'].values])
答案 1 :(得分:0)
直接在编码器上使用输出格式设置选项:
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
答案 2 :(得分:0)
这就是答案。
语言:Objective-C
NSString+PrettyPrint.h
@interface NSString (PrettyPrint)
+ (NSString * _Nonnull)prettifiedJsonStringFromData:(nullable NSData *)data;
+ (NSString * _Nonnull)prettifiedStringFromDictionary:(nullable NSDictionary *)dictionary;
@end
NSString+PrettyPrint.m
#import "NSString+PrettyPrint.h"
@implementation NSString (PrettyPrint)
+ (NSString *)prettifiedStringFromDictionary:(nullable NSDictionary *)dictionary {
if (dictionary == nil) { return @"nil"; }
NSMutableString *returnStr = [NSMutableString stringWithString:@"[ \n"];
for (NSString *key in dictionary) {
[returnStr appendFormat:@" %@: %@,\n", key, [dictionary valueForKey:key]];
}
[returnStr appendFormat:@"]"];
return returnStr;
}
+ (NSString *)prettifiedJsonStringFromData:(nullable NSData *)data {
if (data == nil) { return @"nil"; }
NSData *jsonData;
NSError *error = nil;
NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
if (jsonObject == nil) {
return @"nil (json object from data)";
} else {
BOOL isValidJsonObject = [NSJSONSerialization isValidJSONObject:jsonObject];
if (isValidJsonObject) {
NSData *finalData = [NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:&error];
//TODO: error description
NSString *prettyJson = [[NSString alloc] initWithData:finalData encoding:NSUTF8StringEncoding];
return prettyJson;
} else {
return [NSString stringWithFormat:@"%@\n%@", jsonStr, @" (⚠️ Invalid json object ⚠️)\n"];
}
}
}
@end
然后在需要使用方法时调用它们。
ex1。为正文、响应等打印 NSData
NSLog(@"body: %@", [NSString prettifiedJsonStringFromData:[request HTTPBody]]);
ex2。打印 NSDictionary
NSLog(@"headers: %@", [NSString prettifiedStringFromDictionary:[request allHTTPHeaderFields]]);
可能你会在日志中得到这些结果。
答案 3 :(得分:-1)
我无法想到比原生类型漂亮的东西。
SELECT v.seller_number, v.date_visit, v.city_visited, v.status
FROM visit v
WHERE (v.seller_number, v.date_visit) IN
(SELECT v2.seller_number, MAX(v2.date_visit)
FROM visit v2
GROUP BY v2.seller_number
)
LIMIT 500;