Home > other >  How can I extract a specific section of a JSON string using a regex in Python?
How can I extract a specific section of a JSON string using a regex in Python?

Time:11-11

so i have a string which looks like this (for example) :

{"e":"kline","E":1636631940480,"s":"EPSUSDT","k":{"t":1636631880000,"T":1636631939999,"s":"EPSUSDT","i":"1m","f":15980499,"L":15980734,"o":"0.56630000","c":"0.57200000","h":"0.57300000","l":"0.56630000","v":"280740.00000000","n":236,"x":true,"q":"159924.80310000","V":"150693.00000000","Q":"85802.85780000","B":"0"}}

I am trying to extract certain values from it, lets say i want regex to return "c":"0.57200000" or just the value of 0.57200000.

I tried this code (at least to be able to get "c") but it gives me nothing :

re.search(r'^\"c\",$', resp) # resp is the string variable

Im new to regex and even after 2 hours of searching, im still unable to do it...

CodePudding user response:

Your string is a valid JSON content, so load it as a python structure : dict, then access the data using the keys k and c

import json

value = '{"e":"kline","E":1636631940480,"s":"EPSUSDT","k":{"t":1636631880000,"T":1636631939999,' \
        '"s":"EPSUSDT","i":"1m","f":15980499,"L":15980734,"o":"0.56630000","c":"0.57200000",' \
        '"h":"0.57300000","l":"0.56630000","v":"280740.00000000","n":236,"x":true,' \
        '"q":"159924.80310000","V":"150693.00000000","Q":"85802.85780000","B":"0"}}'

value = json.loads(value)
print(value['k']['c'])  # 0.57200000

CodePudding user response:

You are trying to get some value from dict not string.

    dict = {"e": "kline", "E":1636631940480,"s":"EPSUSDT","k":{"t":1636631880000,"T":1636631939999,"s":"EPSUSDT","i":"1m","f":15980499,"L":15980734,"o":"0.56630000","c":"0.57200000","h":"0.57300000","l":"0.56630000","v":"280740.00000000","n":236,"x":True,"q":"159924.80310000","V":"150693.00000000","Q":"85802.85780000","B":"0"}}

print(dict["k"]["c"])
  • Related