AJS
AJS

Reputation: 11

how to print from json file using python

I have a json file url - http://****

and want to print ticket price and id from it. I am stuck & do not know how to proceed.

The code I have is

#!/usr/bin/python
import json
from pprint import pprint
json_data=open('./test.json')
data= json.load(json_data)
pprint(data)
json_data.close()

With the above code , i am getting output as

 [{u'currency': u'USD',
 u'exchange': u'USNASD',
 u'id': u'CA98420N1050',
 u'name': u'Xenon Pharmaceuticals Inc',
 u'price': 7.85,
 u'ticker': u'XENE'},
 {u'currency': u'EUR',
 u'exchange': u'XDUB',
 u'id': u'IE0003295239',
 u'name': u'FYFFES PLC',
 u'price': 1.47}]

I dont kow why I am getting U as output and I know want ticker, id and price from this file. Help!

Upvotes: 1

Views: 986

Answers (3)

Sharvin26
Sharvin26

Reputation: 3101

Well, you can use:

data = json.loads(json_data)
print(json.dumps(data,indent=4,sort_keys=True))

This will give you the output in indented format.

Upvotes: 1

iElden
iElden

Reputation: 1280

import json

with open("marketdata.json") as fd:
    data = json.load(fd)

for i in data:
    print("{ticker}|{id}|{price}".format(**i))

Learn more about .format() in this doc:

Upvotes: 1

jpadd009
jpadd009

Reputation: 45

You need to parse the JSON object:

import json

def parseJSON(jsonObj):
    parsed_json = json.load(jsonObj)
    return parsed_json

parsedJson = parseJson(<your_json_obj>)+

Upvotes: 1

Related Questions