解析没有统一的JSON Python

时间:2018-05-22 07:00:32

标签: python json

我无法获得" remoteAddress"只有在我需要的时候。此输出由另一个API生成,因此我无法对其进行编辑。为了清楚起见,我想分割2个过程的数据。对不起,如果它是重新发布,我找不到类似的帖子。

  Select inv.InvoiceNo, inv.EntryDateTime, s.ServiceName, c.VehicleRegNo, inv.ServicePrice, c.CustomerName, inv.fk_BookingID
    from dbo.[Services] s
    inner join invoices inv
    on inv.fk_ServiceID= s.ServiceID
    inner join customers c
    on c.CustomerID= inv.fk_CustomerID
    Cross join (Select SUM(inc.ServicePrice) as TotalCost from dbo.Invoices inc ) t
    where Convert(varchar(11), inv.EntryDateTime, 106) between @FromDate and @ToDate

编辑:它需要是动态的,所以我不能只搜索" remoteAddress"。我正在解析GRR流,不同的流具有可能丢失的不同密钥。

2 个答案:

答案 0 :(得分:0)

使用dict.get

<强>实施例

data = [{
   "family": "INET6",
   "pid": 835,
   "localAddress": {
       "ip": "127.0.0.1",
       "port": 44082
   },
   "processName": "avahi-daemon",
   "state": "NONE",
   "type": "SOCK_DGRAM"
},
{
   "family": "INET",
   "pid": 22624,
   "localAddress": {
       "ip": "0.0.0.0",
       "port": 631
   },
   "remoteAddress": {
       "ip": "x.x.x.x",
       "port": 443
   },
   "processName": "gitkraken",
   "state": "ESTABLISHED",
   "type": "SOCK_STREAM"
 }
]
res = [i.get("remoteAddress") for i in data]
print(res)
print(filter(None, res))

<强>输出:

[None, {'ip': 'x.x.x.x', 'port': 443}]
[{'ip': 'x.x.x.x', 'port': 443}]

答案 1 :(得分:0)

假设这两个词典存储在列表中,例如

data = [{
   "family": "INET6",
   "pid": 835,
   "localAddress": {
       "ip": "127.0.0.1",
       "port": 44082
   },
   "processName": "avahi-daemon",
   "state": "NONE",
   "type": "SOCK_DGRAM"
},
{
   "family": "INET",
   "pid": 22624,
   "localAddress": {
       "ip": "0.0.0.0",
       "port": 631
   },
   "remoteAddress": {
       "ip": "x.x.x.x",
       "port": 443
   },
   "processName": "gitkraken",
   "state": "ESTABLISHED",
   "type": "SOCK_STREAM"
 }]

然后此代码应返回“远程地址”中存储的

for dictionary in data:
    if "remoteAddress" in dictionary:
        print(dictionary.get("remoteAddress"))