首页 > 解决方案 > Angular9字符串到数组

问题描述

我有一个熊猫系列,我已将其转换为 JSON 以便 Angular 显示在表格中。问题是键值是字符串类型下的 python 列表。如何将密钥转换为 Angular 的数组?

JSON:

{ 
"result": {
    "('', '100.83.105.90')": 1, 
    "('AS1124 Universiteit van Amsterdam', '145.18.162.122')": 2, 
    "('AS11796 Airstream Communications, LLC', '64.33.197.15')": 1, 
    "('AS16276 OVH SAS', '51.75.201.126')": 1, 
    "('AS209 CenturyLink Communications, LLC', '174.27.155.12')": 1, 
    "('AS22394 Cellco Partnership DBA Verizon Wireless', '174.241.2.88')": 1, 
    "('AS24608 Wind Tre S.p.A.', '37.227.23.201')": 1, 
    "('AS3329 Vodafone-panafon Hellenic Telecommunications Company SA', '5.55.162.202')": 1, 
    "('AS3352 Telefonica De Espana', '80.24.64.41')": 1, 
    "('AS6128 Cablevision Systems Corp.', '69.116.62.88')": 1, 
    "('AS6805 Telefonica Germany', '2.240.20.127')": 1, 
}

在角:

<table class="table">
    <thead class="thead-dark">
        <tr>
            <th scope="col" >{{selectedGroup}}</th>
            <th scope="col">{{selectedColumn}}</th>
            <th scope="col">Hits</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let item of mvaHits | keyvalue">
            <td>{{item.key[0]}}</td> 
            <td>{{item.key[1]}}</td> 
            <td>{{item.value}}</td>
        </tr>
    </tbody>
</table>

它看起来像什么: 在此处输入图像描述

我怎样才能解决这个问题?

感谢帮助:)

标签: jsonangularjsangularpandas

解决方案


最好的解决方案是以适当的 JSON 格式从 Python 导出数据。然后,您可以使用JSON.parse().

如果您无法调整mvaHits,这应该将 Python 数组解析为 Javascript 数组,并让您访问数组中的元素。请注意,这并非在所有情况下都有效,特别是如果您的数组中的字符串有逗号。为了清晰和整洁,我建议不要在 HTML 中进行这些转换,而是mvaHits在第一次加载时进行。但这应该有效:

<table class="table">
    <thead class="thead-dark">
        <tr>
            <th scope="col" >{{selectedGroup}}</th>
            <th scope="col">{{selectedColumn}}</th>
            <th scope="col">Hits</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let item of mvaHits | keyvalue">
            <td>{{item.key.slice(1,-1).split(', ').map((s) => s.slice(1,-1))[0]}}</td> 
            <td>{{item.key.slice(1,-1).split(', ').map((s) => s.slice(1,-1))[1]}}</td> 
            <td>{{item.value}}</td>
        </tr>
    </tbody>
</table>

分解它:

item.key
    .slice(1,-1) // Removes the first and last characters in the string, removing the ()
    .split(', ') // Splits the string into an array using ', ' as the delimiter
    .map((s) => s.slice(1,-1)) // Removes the quotes from the strings in the array
    [0] // access the first element of the new array

推荐阅读