1

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!

2
  • 2
    The "u"s are normal. That's how Python lets you know they're Unicode strings. If you really don't like them, you can upgrade to Python 3.X and they'll go away :-) Commented Nov 16, 2018 at 18:38
  • @ajs it looks like you're outsourcing answering an interview question: This should be treated as confidential and not posted publicly. i.e. don't post this on Stack Overflow or share Commented Nov 16, 2018 at 18:53

3 Answers 3

1

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>)+
Sign up to request clarification or add additional context in comments.

Comments

1
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:

2 Comments

{ubuntu@ubuntu:~/json$ cat github.py #!/usr/bin/python import json with open("test.json") as fd: data = json.load(fd) for i in data: print("{ticker}|{id}|{price}".format(**i)) } while running the code, getting following error --- Is it due to wrong formatting command ? { ubuntu@ubuntu:~/json$ python github.py Traceback (most recent call last): File "github.py", line 9, in <module> print("{ticker}|{id}|{price}".format(**i)) TypeError: format() argument after ** must be a mapping, not unicode }
This gives me output as {TSTIF|CA8730151013|1.866 XENE|CA98420N1050|7.85 Traceback (most recent call last): File "ateet1.py", line 6, in <module> print("{ticker}|{id}|{price}".format(**i)) KeyError: 'ticker' } i need output in json format
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.