【问题标题】:how to format json in angular如何以角度格式化json
【发布时间】:2021-09-28 08:10:30
【问题描述】:

我想知道如何使用带有 Angular 框架的打字稿来格式化我的 json 以具有键和值,

如果我在我的 html 中使用 keyvalue 管道,使用当前方法它会起作用,但我想格式化 json。

在下面的示例中,我有我当前的 json 和预期的 json,以便您可以看到我期望的结果,并尽可能清楚地作为我想要明确的业务的初学者

Current.json

{
  "url": "url test"
  "flight": [
   [
    "1", 
    "apollo",
    "ariane"
   ],
   [
    "2",
    "Space X",
    "Boca chica"
   ]
  ]
}

expected.json // 这个json就是我想要的

{
      "url": "url test"
      "flight": [
       [
        id: "1", 
        name: "apollo",
        rocket:"ariane"
       ],
       [
        id: "2",
        name: "Space X",
        rocket: "falcon 9"
       ]
      ]
    }

ts.file

get() {
 this.service.get().subscribe((data: Interface[])=> {
  this.array = data
 });

【问题讨论】:

  • expected.json 不是有效的 JSON。
  • 这不可能吗? @evolutionxbox
  • 不是 JSON 没有。 JSON 有一个特定的格式可以遵循。有关详细信息,请参阅 json.org,或使用 jsonlint.com 进行检查。 --- 你的意思可能是“JS 对象”,而不是 json?

标签: javascript json angular typescript


【解决方案1】:

您期望的 Json 无效,如果您想要这些数组值的属性名称,您需要将它们设为对象。

{
  "url": "url test"
  "flight": [
   {
    id: "1", 
    name: "apollo",
    rocket:"ariane"
   },
   {
    id: "2",
    name: "Space X",
    rocket: "falcon 9"
   }
  ]
 }

要从您提供的示例中获取此格式,您可以这样做:

get() {
  this.service.get().subscribe((data: Interface[])=> {
  data.flight = data.flight.map(f => ({id: f[0], name: f[1], rocket: f[2]}))
  this.array = data
});

【讨论】:

  • 那仍然是无效的 JSON?
  • 我收到此错误:“任何 []”类型上不存在属性航班,为什么?
【解决方案2】:

请试试这个代码sn-p

 get() {
   this.service.get().subscribe((data: any)=> {
   data.flight = data.flight.map(f => {
        return {id: f[0], name: f[1], rocket: f[2]}
    })
    this.array = data
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    相关资源
    最近更新 更多