2

I have this Json, and I need a value from a rate.

 "_id" : ObjectId("5addb57d0043582d48ba898a"),
"success" : true,
"timestamp" : 1524477784,
"base" : "EUR",
"date" : "2018-04-23",
"rates" : {
    "AED" : 4.492662,
    "AFN" : 85.576329,
    "ALL" : 128.39508,
    "AMD" : 586.837094,
    "ANG" : 2.177608,
    "AOA" : 267.092358,
    "ARS" : 24.678283,
    "AUD" : 1.602032,
    "AWG" : 2.177639,
    "AZN" : 2.079155,
    "BAM" : 1.958775,
    "BBD" : 2.446786,
    "BDT" : 101.517146,
    "BGN" : 1.943843,
    "BHD" : 0.460968,
    "NOK" : 9.626194,
 }

And this is my Python code

import pymongo

uri = "mongodb://127.0.0.1:27017"
client = pymongo.MongoClient(uri)
database = client['db']
collection = database['currency']
collection2 = database['countries']
p = str(input('Insert the country: ')).capitalize()

if p=='Norway':
currency = collection.find_one({'NOK'})
print(currency)

I want to print the value inside de NOK, how can I do it? Thanks in advance.

2 Answers 2

1

I think you can call it by :

currency = collection.find_one({"NOK"})
print(currency['rates']['NOK'])
Sign up to request clarification or add additional context in comments.

1 Comment

It worked like this: currency = collection.find_one({}) print(currency['rates']['NOK']) Thanks!
1

What you're trying to do is fetch a value in a dictionary which is integrated inside of another dictionary. JSON returns are dictionaries.

I imagine that the collection variable contains the JSON return

One way of fetching this data is by calling the dictionary and telling it what key you want the dictionary to return, as the "NOK" key is in the "rates" key we will be calling the rates key first, then when the dictionary has returned the dictionary that contains the "NOK" key we will then pass the "NOK" key to that returned dictionary, so the code looks like this:

    currency = collection["rates"]["NOK"]

Another way of doing this is using the for loop, it is a lot longer but may help you understand.

    for key in collection:
        if key == "rates":
            for keyRates in JSON[key]:
                if keyRates == "NOK":
                     currency = JSON[key][keyRates]

Hope this helps

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.