将Javascript数组转换为JSON FILe

时间:2019-02-12 19:00:59

标签: javascript json

我有这个Javascript数组:

  const myQuestions = [
    {
      question: "Question 1?",
      answers: {
        a: "A",
        b: "B",
        c: "The Correct One"
      },
      correctAnswer: "c"
    },
    {
      question: "Question 2?",
      answers: {
        a: "A",
        b: "B",
        c: "The Correct One"
      },
      correctAnswer: "c"
    }
  ];

我想将其转换为JSON文件,以便可以执行以下操作:

myQuestions=myjsonfile.json() ...那有可能吗?如果可以,怎么办?

我只是尝试将所有数组放在某个{}之间,然后从中制作一个json文件,但没有成功,我也不知道为什么

我的问题是:

我该如何做才能从某个URL提取json文件,然后使该变量与json文件相同?

2 个答案:

答案 0 :(得分:2)

JSON.stringify()将javascript对象转换为格式正确的JSON字符串。它可以是任何单个对象或数组。您不需要将所有键名都用引号引起来,也不需要格式化对象以准备转换为字符串,它只需要有效的javascript数据(不包含函数或循环引用)即可。

JSON.parse()进行相反操作,将JSON字符串转换为可用对象。 (parse() 的输入必须是字符串,而不是已经是对象的东西。)

const myQuestions = [
    {
      question: "Question 1?",
      answers: {
        a: "A",
        b: "B",
        c: "The Correct One"
      },
      correctAnswer: "c"
    },
    {
      question: "Question 2?",
      answers: {
        a: "A",
        b: "B",
        c: "The Correct One"
      },
      correctAnswer: "c"
    }
  ];
  
let jsonString = JSON.stringify(myQuestions)
console.log(jsonString) // You can store that string as a .json file

let parsedObject = JSON.parse(jsonString) // convert the string back to an object
console.log(parsedObject[1].answers.c) // it's a plain JS object now

许多人对JSON感到困惑的原因是,有太多的开发人员将术语与它所代表的对象互换使用。 JSON是可以转换为数据对象的字符串。可以将一个对象转换为JSON字符串,但是它们不是同一回事。

例如,JSON.parse({"this": "is an object"})无效,因为它的输入已经是一个对象,不需要对其进行解析。正确,那应该是JSON.parse('{"this": "is a string"}')

类似地,当通过ajax获取JSON时,您正在加载的字符串必须为parsed()

var myQuestions; 
// error handling and response status checking skipped here for brevity
fetch('someurltoaJsonFile.json').then(response => { 
   myQuestions = JSON.parse(response.data) // convert response string to object
   // do stuff with myQuestions object here
})
// (not here, because it hasn't arrived yet)

答案 1 :(得分:0)

Json文件应该包含有效的JSON,仅此而已。您可以通过JSON.stringify(myQuestions)生成它:

[{"question":"Question 1?","answers":{"a":"A","b":"B","c":"The Correct One"},"correctAnswer":"c"},{"question":"Question 2?","answers":{"a":"A","b":"B","c":"The Correct One"},"correctAnswer":"c"}]