我想在data.json文件中调用对象

时间:2018-08-05 17:57:30

标签: javascript json parsing object

我想调用data.json文件中的对象

My File

以我的getData.js为例:

var data = JSON.parse(data.json);
alert(data['name']);

我该怎么做?

2 个答案:

答案 0 :(得分:0)

这是从JSON对象获取值的方式,我使用了来自jsonplaceholder https://jsonplaceholder.typicode.com/users

的虚拟JSON对象

class Choices:
    rock = "Rock"
    paper = 'Paper'
    scissors = 'Scissors'

def rps_game():

    # Getting the name of the player.
    name = raw_input("Welcome to Rock Paper Scissors Game!\n Enter your name:")

    # The Players Choice.
    while True:

        player_choice = raw_input("\n1-Rock\n2-Paper\n3-Scissors\n{} choose a number:".format(name))
        int(player_choice)

        if player_choice == 1:
            player_choice = Choices.rock
        if player_choice == 2:
            player_choice = Choices.paper
        if player_choice == 3:
            player_choice = Choices.scissors


    # Getting the cpu choice.
        cpu_choice = random.randint(1, 3)
        if cpu_choice == 1:
            cpu_choice = Choices.rock
        if cpu_choice == 2:
            cpu_choice = Choices.paper
        if cpu_choice == 3:
            cpu_choice = Choices.scissors


        if player_choice == cpu_choice:
            print"\n Its a Tie!/n{} you!".format(name)

        if player_choice == Choices.paper and cpu_choice == Choices.rock:
            print"\n Congratulations!\n{} you won!".format(name)

        if player_choice == Choices.scissors and cpu_choice == Choices.paper:
            print"\n Congratulations!\n{} you won!".format(name)

        if player_choice == Choices.rock and cpu_choice == Choices.scissors:
            print"\n Congratulations!\n{} you won!".format(name)

        else:
            print"\n Too Bad You Lost!".format(name)



        print "\nCPU Choice: {}\n Your Choice: {}".format(cpu_choice, player_choice)

        play_again = raw_input("Want to Play Again? y/n")
        if play_again == 'y':
            continue
        else:
            break

答案 1 :(得分:0)

Node.js 您需要使用fs,这是库帮助才能使用文件。然后读取文件。      var fs = require('fs'); var obj; fs.readFile('data.json', 'utf8', function (err, data) { if (err) throw err; obj = JSON.parse(data); });

使用jQuery http://api.jquery.com/jQuery.getJSON/

$.getJSON("test.json", function(json) { console.log(json); // this will show the info it in firebug console });