问题描述
我有一个函数可以接收一个选择文本,它是一个未格式化的 JSON 代码,我正在尝试使用 stringify 方法将 JSON 代码格式化为一个(漂亮的)视图。这是代码:
import SwiftUI
struct AddTasks: View {
@State var data = 0
@State var taskName = ""
@State private var prioritySelectedHigh : Bool = false
@State private var prioritySelectedMed : Bool = false
@State private var prioritySelectedLow : Bool = false
@State private var priority : String = ""
var items = [1,2,3,4,5,6,7,8,9,10]
var body: some View {
NavigationView {
vstack(alignment:.center,spacing: 30){
ZStack {
RoundedRectangle(cornerRadius: 9)
.foregroundColor(Color("TabBar "))
.opacity(0.7)
.frame(width: 310,height: 60,alignment: .center)
TextField(" Task Name ",text: $taskName)
.frame(width: 270,alignment: .center)
}
// These Buttons dont work
HStack(alignment: .center,spacing: 52){
ZStack {
RoundedRectangle(cornerRadius: 9)
.foregroundColor(.pink)
.opacity(0.2)
.frame(width: 70,height: 40,alignment: .center)
Button(action: {
print("Hi")
},label: {
Text("High")
.font(.system(size: 18))
.foregroundColor(.red)
})
}
ZStack {
RoundedRectangle(cornerRadius: 9)
.foregroundColor(.orange)
.opacity(0.2)
.frame(width: 70,alignment: .center)
Button(action: {},label: {
Text("Med")
.font(.system(size: 18))
.foregroundColor(.orange)
})
}
ZStack {
RoundedRectangle(cornerRadius: 9)
.foregroundColor(.green)
.opacity(0.2)
.frame(width: 70,alignment: .center)
Button(action:{},label: {
Text("Low")
.font(.system(size: 18))
.foregroundColor(.green)
})
}
}
ZStack {
RoundedRectangle(cornerRadius: 9)
.foregroundColor(Color("TabBar "))
.opacity(0.7)
.frame(width: 310,alignment: .center)
Picker(selection: $data,label: Text("Data"),content: {
ForEach(items,id:\.self) { item in
Text("\(item)")
.rotationEffect(Angle(degrees: 90))
}
})
.labelsHidden()
.rotationEffect(Angle(degrees: -90))
.frame(maxHeight: 60)
.clipped()
.foregroundColor(Color("AccentColor"))
.font(.system(size: 20))
}
}.navigationTitle("New Task")
}.environment(\.colorScheme,.dark)
}
}
struct AddTasks_Previews: PreviewProvider {
static var previews: some View {
AddTasks()
// .environment(\.colorScheme,.dark)
}
}
这是未格式化的 JSON 代码:
function prettyPrintJSON(selectionInfo) {
const unformattedJSON = selectionInfo.selectionText
const formattedJSON = JSON.stringify(unformattedJSON,null,'\t')
}
如您所见,它没有格式化。另外,我在 google chrome 扩展上使用它,并使用 vue.js 作为框架来构建一个表,以在同一个表中输出不同类型的数据。任何想法我错过了什么?谢谢
解决方法
把那个 \t
变成一个数字来表示你想要多少个缩进空格
let json = {"colors":[{"color":"black","category":"hue","type":"primary","code":{"rgba":[255,255,1],"hex":"#000"}},{"color":"white","category":"value","code":{"rgba":[0,"hex":"#FFF"}},{"color":"red","hex":"#FF0"}},{"color":"blue","hex":"#00F"}},{"color":"yellow",{"color":"green","type":"secondary","hex":"#0F0"}}]}
;
console.log(JSON.stringify(json,null,2)); // spacing level = 2);