简体   繁体   中英

How can I get a specific value from a JSON URL, and pass it into a Javascript variable?

I want to use a JSON URL to get up-to-date exchange rates for use in a webpage. For this I want to be able to get a specific exchange rate (say, US Dollar) and pass the rate onto a variable so I can use it in a JS function.

Here is a sample of the JSON code:

"rates": {
    "AED": 3.672796,
    "AFN": 57.951451,
    "ALL": 112.589601,
    "AMD": 430.416,
    "ANG": 1.787,
    "AOA": 100.82775,
    "ARS": 8.52454,
    "AUD": 1.175504,
    "AWG": 1.79,
    "AZN": 0.784233,
    "BAM": 1.571689,
    "BBD": 2

Assign the JSON code to a variable, eg var json = "{your json string}" then parse it with var obj = JSON.parse( json ); . Now you can access the elements from obj .

Use JSON.stringify to turn a JavaScript variable into a JSON string and JSON.parse to do the opposite. Then you can access properties directly (obj.SomeProperty) or dynamically (obj["SomeProperty"].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM