2016-07-22 1 views
1

Я стараюсь, чтобы пользователь сделал выбор и основываясь на этом выборе, я просверлю данные JSON и отображу выбранную информацию. В конечном итоге я хотел бы создать раскрывающийся список в html и прослушивателе событий в Javascript, который затем будет извлекаться.извлекать данные JSON на основе пользовательского выбора/подсказки

var userOcean = prompt("Will you be fishing in the gulf or atlantic ?"); 

var userFish = prompt("What fish do you want to look up?"); 

console.log(
    "\n\nfish: "+jsonObject.ocean_measure.userOcean.fish.userFish.name+ 
    "\n\nlength: "+jsonObject.ocean_measure.userOcean.fish.userFish.length+ 
    "\n\nclosed: "+jsonObject.ocean_measure.userOcean.fish.userFish.closed+ 
    "\n\nlimit: "+jsonObject.ocean_measure.userOcean.fish.userFish.limit+ 
    "\n\nremarks: "+jsonObject.ocean_measure.userOcean.fish.userFish.remarks 
    ); 

выше, является Javascript и ниже данные JSON

var jsonObject = { 
"ocean_measure" : 
    { 
    "gulf": 
     { 
      "fish": { 
       "dolphin": { 
        "name": "Mahi-mahi", 
        "length": "none", 
        "limit": "10 per person or 60 per vessel whichever is less" 
       }, 
       "blackfin tuna": { 
        "name": "Blackfin Tuna", 
        "length": "not regulated", 
        "limit": "The default bag limit for all unregulated species is two fish or 100 pounds per day, whichever is more" 
       }, 
       "snook": { 
        "name": "Snook", 
        "length": "Not less than 28 inches total length (TL) or more than 33 inches TL", 
        "closed": "Dec. 1-end of February; May 1-Aug. 31", 
        "limit": "1 per harvester per day", 
        "remarks": "Snook permit required for harvest when saltwater license required. State regulations apply in federal waters. Illegal to buy or sell snook. Fish must remain in whole condition until landed ashore (heads, fins, and tails intact). Snatch hooks and spearing prohibited. Harvest prohibited by or with the use of any multiple hook in conjuction with live or dead bait." 
       } 
      } 
     } 
    , 
    "atlantic": 
     { 
      "fish": { 
       "dolphin": { 
        "name": "Mahi-mahi", 
        "length": "20 inches fork length", 
        "limit": "10 per person or 60 per vessel whichever is less" 
       }, 
       "blackfin tuna": { 
        "name": "Blackfin Tuna", 
        "length": "not Regulated", 
        "limit": "The default bag limit for all unregulated species is two fish or 100 pounds per day, whichever is more" 
       }, 
       "snook": { 
        "name": "Snook", 
        "length": "Not less than 28 inches total length (TL) or more than 32 inches TL", 
        "closed": "Dec. 15 to Jan. 31, June 1 to Aug. 31", 
        "limit": "1 per harvester per day", 
        "remarks": "Snook permit required for harvest when saltwater license required. State regulations apply in federal waters. Illegal to buy or sell snook. Fish must remain in whole condition until landed ashore (heads, fins, and tails intact). Snatch hooks and spearing prohibited. Harvest prohibited by or with the use of any multiple hook in conjuction with live or dead bait." 
       } 
      } 
     } 
    } 
} 

Я не смог найти простой способ взять UserInput и создать выборку данных с ним из JSON файла.

ответ

0

Вы получили это почти правильно, но если вы хотите использовать переменную при обращении объект, который вы должны сделать это таким образом:

jsonObject.ocean_measure[userOcean].fish[userFish].name

Fixed console.log функция:

console.log(
    "\n\nfish: "+jsonObject.ocean_measure[userOcean].fish[userFish].name+ 
    "\n\nlength: "+jsonObject.ocean_measure[userOcean].fish[userFish].length+ 
    "\n\nclosed: "+jsonObject.ocean_measure[userOcean].fish[userFish].closed+ 
    "\n\nlimit: "+jsonObject.ocean_measure[userOcean].fish[userFish].limit+ 
    "\n\nremarks: "+jsonObject.ocean_measure[userOcean].fish[userFish].remarks 
); 

Также, JSFiddle

+0

У меня есть «Часть вторая», если вы к этому небольшое приложение I» m работать, если вы хотите здесь, это ссылка на этот вопрос. http://stackoverflow.com/questions/38545522/html-select-value-passed-into-javascript-var-then-used-to-fetch-json – Carl

0

Чтобы использовать содержимое переменной для доступа к свойствам объекта, вы должны использовать то, что называется bracket notation:

ocean_measure.gulf == ocean_measure["gulf"] 

Это происходит из-за того, что в Javascript, объекты действуют как словари в том, что их свойства и методы могут быть доступны с ключами, ключом является именем свойства или методы.

Для того, чтобы выбор пользователя, в качестве переменной, должен быть выбран из объекта, поместите переменную в скобках:

userOcean = "gulf" 
ocean_measure[userOcean] == ocean_measure["gulf"] 
Смежные вопросы