Home > database >  How to parse data from API?
How to parse data from API?

Time:07-13

Am getting API response Like Below

https://imgur.com/a/uVcLfF4

{'s': 'ok', 'd': 
[
    {'n': 'NSE:SBIN22JUL485CE', 's': 'ok', 'v': {'ch': -2.25, 'chp': -17.05, 'lp': 10.95, 'spread': 0.25, 'ask': 10.95, 'bid': 10.7, 'open_price': 11.5, 'high_price': 15.05, 'low_price': 10.45, 'prev_close_price': 13.2, 'volume': 1161000, 'short_name': 'SBIN22JUL485CE', 'exchange': 'NSE', 'description': 'NSE:SBIN22JUL485CE', 'original_name': 'NSE:SBIN22JUL485CE', 'symbol': 'NSE:SBIN22JUL485CE', 'fyToken': '1011220728149794', 'tt': 1657584000, 'cmd': {'t': 1657620000, 'o': 10.95, 'h': 10.95, 'l': 10.95, 'c': 10.95, 'v': 1500, 'tf': '15:30'}}
    }, 
    {'n': 'NSE:SBIN22JUL480CE', 's': 'ok', 'v': {'ch': -2.65, 'chp': -16.46, 'lp': 13.45, 'spread': 0.1, 'ask':
     13.45, 'bid': 13.35, 'open_price': 15.3, 'high_price': 18.45, 'low_price': 12.9, 'prev_close_price': 16.1, 'volume': 4270500, 'short_name': 'SBIN22JUL480CE', 'exchange': 'NSE', 'description': 'NSE:SBIN22JUL480CE', 'original_name': 'NSE:SBIN22JUL480CE', 'symbol': 'NSE:SBIN22JUL480CE', 'fyToken': '1011220728128799', 'tt': 1657584000, 'cmd': {'t': 1657619940, 'o': 13.45, 'h': 13.45, 'l': 13.45, 'c': 13.45, 'v': 28500, 'tf': '15:29'}}
    }
]

}

How to read and print this in python like below.

Name= NSE:SBIN22JUL485CE
ch = -2.25
chp = -17.05
volume = 1161000

Name= NSE:SBIN22JUL480CE
ch = -2.65
chp = -16.46
volume = 4270500

CodePudding user response:

It looks like json, if you have that text in a variable, you can use the python json librarie for decoding it, and get a dictionary.

import json

text = '...' # The variable that contains the response

data = json.loads(text)
for entry in data['d']:
    print(f'Name = {entry["n"]}')
    print(f'ch = {entry["v"]["ch"]}')
    print(f'chp = {entry["v"]["chp"]}')
    print(f'volume = {entry["v"]["volume"]}')
    print('')

If for some reason, in the text, the quotes are single quotes ' insted of double ", you should need to replace it, before the json parsing:

text = text.replace("'", '"')

CodePudding user response:

If it is already a dict, just print the content:

mydict = <API response>
if 's' in mydict and mydict['s'] == 'ok':
    for data in mydict['d']:
        print('Name:', data['n'])
        print('ch:', data['v']['ch'])
        print('chp:', data['v']['chp'])
        print('volume:', data['v']['volume'])
        print()

If it is not a dict then you need to convert the content before:

import json
content = <API response>
mydict = json.loads(content)
<code to print above>
  • Related