简体   繁体   English

Json操作TypeScript Angular 2

[英]Json manipulation TypeScript Angular 2

I come from a Python Background and recently started programming using TypeScript and Angular2. 我来自Python背景,最近开始使用TypeScript和Angular2进行编程。 I want to know how to obtain keys from a JSON object using TypeScript. 我想知道如何使用TypeScript从JSON对象获取密钥。 I have a response like so: 我有这样的回应:

response.text()

I pass this object to a function 我将此对象传递给一个函数

removeMetaData (my_data: string){
    //(Various manipulation)...etc
}

i have read that I can call a json() method instead of text() . 我已经读过我可以调用json()方法而不是text() If I do that, what is the type I should use for my_data ? 如果这样做,应为my_data使用什么类型?

Then, If my JSON looks like this: 然后,如果我的JSON如下所示:

{
    "count": 100,
    "next_page": "http://www.test.com/users/?page=2", 
    "prev_page": "http://www.test.com/users/?page=3", 
     "results":[
     {
          "username": "johnny"
     },
     Etc....

     ]

How do I parse that? 我该如何解析? I've read I might have to use an interface but I don't understand how. 我读过我可能不得不使用一个接口,但是我不知道如何。

In python it's just response["next_page"] to get the key of a dictionary, then I can assign that value to a variable within the class. 在python中,它只是response["next_page"]以获取字典的键,然后可以将该值分配给类中的变量。 That is exactly what I'm trying to achieve within a component. 这正是我要在组件中实现的目标。

Thank you. 谢谢。

ADDITION 加成

list() {
    this.requestService.get(this.api_path)
    .subscribe(
    response => this.populate(response.json()),
    error => this.response = error.text()
    )

}

populate(payload: object) {
    this.count = payload.count;
    this.next = payload.next;
    this.previous = payload.previous;
   *payload.results => this.users = payload.results;******
}

Declare an interface which will be used as value object. 声明一个将用作值对象的接口。

export interface IPage
{
 count:number;
next_page:string;
prev_page:string;
results:Array<any>;
...
...
}

var my_data:IPage;

Now assign parsed json value to my_data and access all the properties with '.' 现在将已解析的json值分配给my_data并使用'。'访问所有属性。 operator ie my_data.count, my_data.results . 运算符,即my_data.count, my_data.results

Feel free to throw any question. 随时提出任何问题。

If I do that, what is the type I should use for my_data? 如果这样做,应该为my_data使用哪种类型?

Its just a javascript object. 它只是一个javascript对象。

As an example if you json looks like: 例如,如果您的json看起来像:

{
  "foo": {
   "bar": "bas"
  }
}

Then in the parsed json (in variable someObj ) the value someObj.foo.bar would be bas 🌹 然后,在所解析的JSON(在可变someObj )的值someObj.foo.bar将是bas 🌹

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM