How to extract specific value from received message via Websocket?

Asked

Viewed 41 times

0

I’m trying to extract the "balance" from a JSON. I would like to know how I can do this in a direct way, without receiving this complete message, which ends up being giant, but rather extract only the value I want.

import websocket
import json

def on_open(ws):
    json_data = json.dumps({"authorize": "Vn55jnImK7UzcYr"}) # valor apenas de exemplo
    ws.send(json_data)

def on_message(ws, message):
    print('Dados: %s' % message)

if __name__ == "__main__":
    apiUrl = "wss://ws.binaryws.com/websockets/v3?app_id=1089"
    ws = websocket.WebSocketApp(apiUrl, on_message = on_message, on_open = on_open)
    ws.run_forever()

The printing in IDLE is according to the image below that I cut due the data, but I would like to extract this balance value. For this I would have to manipulate the string? The problem of manipulating the string by taking the specific positions, is that this value can go from 0 to 999999... Then the position would always change. Or has some way to directly receive this amount?

inserir a descrição da imagem aqui

2 answers

2

One solution is to use regex:

import re

result='"balance":10175.95, "country":"br","currency":"USD", "balance":33.52, "country":"br","currency":"USD"'

valores= re.findall(r'(?<!"balance")\d+\.\d{2}',result)

for valor in valores:
    print(valor)

Returns:

10175.95
33.52

For a string co

  • I tried to do so a = message b = json.loads(a) print(b['balance'])

  • That way you put it worked very well. Just a doubt, would be able to extract only the number without it [' ']? Or I’ll still have to manipulate the string?

  • It’s a list. So you can iterate on it. I’ll edit the answer. Anyway, look at the @Paulo Marques answer that presented a simpler solution.

2


If you are sure that the JSON is well assembled, taransforme it into a dictionary

First form ()

>>> texto = '{"codigo": 123, "balance": 10.20, "outro": "qualquer coisa"}'

>>> dict_texto = eval(texto)

>>> dict_texto
{'codigo': 123, 'balance': 10.2, 'outro': 'qualquer coisa'}

>>> dict_texto["balance"]
10.2

Second form (json module)

>>> import json

>>> dict_texto2 = json.loads(texto)

>>> dict_texto2
{'codigo': 123, 'balance': 10.2, 'outro': 'qualquer coisa'}

>>> dict_texto2["balance"]
10.2

Note: The second is much better, because the eval can suffer from malicious code.

  • It closes "]" before "balance", so when I do json.loads, it prints nothing. a = message b = json.loads(a) print(b['balance'])

  • 1

    I couldn’t see the json properly, but it looks like b["authorize"]["balance"]

  • Perfect! It worked, thank you @Paulo Marques.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.