【问题标题】:How to convert json array to java script using php?如何使用 php 将 json 数组转换为 javascript?
【发布时间】:2018-10-08 19:46:00
【问题描述】:

我有这个数据...

    {"quiz":
      [{"question":"What is your favorite color?",
        "choices":[{"prefix":"A","content":"Red"},{"prefix":"B","content":"Blue"},{"prefix":"C","content":"Yellow"},{"prefix":"D","content":"Pink"}]},
       {"question":"What is the equivalent measurement of 1 feet?",
        "choices":[{"prefix":"A","content":"12cm"},{"prefix":"B","content":"12px"},{"prefix":"C","content":"12mm"},{"prefix":"D","content":"12inch"}]},
        {"question":"What is the combination of Green?",
        "choices":[{"prefix":"A","content":"Yellow and Red"},{"prefix":"B","content":"Blue and Orange"},{"prefix":"C","content":"Yellow and Blue"},{"prefix":"D","content":"Black and Skyblue"}]}],"success":1}

我想把它转换成这样的java脚本......

       const myQuestions = [
  {
  question: "Who is the strongest?",
  answers: {
    a: "Superman",
    b: "The Terminator",
    c: "Waluigi, obviously"
  },
  correctAnswer: "c"
},
{
  question: "What is the best site ever created?",
  answers: {
    a: "SitePoint",
    b: "Simple Steps Code",
    c: "Trick question; they're both the best"
  },
  correctAnswer: "c"
},
{
  question: "Where is Waldo really?",
  answers: {
    a: "Antarctica",
    b: "Exploring the Pacific Ocean",
    c: "Sitting in a tree",
    d: "Minding his own business, so stop asking"
  },
  correctAnswer: "d"
}
   ];

我怎样才能做到这一点,因为我正在制作一个测验应用程序,它将通过使用 webviewer 在移动设备中查看。任何帮助都非常感谢..

【问题讨论】:

  • const myQuestions = JSON.parse("{json}");
  • 如何确定什么是correctAnswer

标签: javascript php json


【解决方案1】:

下面是如何转换数组的开始。请注意,您的输入中没有正确答案列,因此无法转换:

var input = {"quiz":
      [{"question":"What is your favorite color?",
        "choices":[{"prefix":"A","content":"Red"},{"prefix":"B","content":"Blue"},{"prefix":"C","content":"Yellow"},{"prefix":"D","content":"Pink"}]},
       {"question":"What is the equivalent measurement of 1 feet?",
        "choices":[{"prefix":"A","content":"12cm"},{"prefix":"B","content":"12px"},{"prefix":"C","content":"12mm"},{"prefix":"D","content":"12inch"}]},
        {"question":"What is the combination of Green?",
        "choices":[{"prefix":"A","content":"Yellow and Red"},{"prefix":"B","content":"Blue and Orange"},{"prefix":"C","content":"Yellow and Blue"},{"prefix":"D","content":"Black and Skyblue"}]}],"success":1}
        
console.log(input.quiz.map(({question, choices}) => ({
  question,
  answers: choices.reduce((obj, v) => Object.assign(obj, {[v.prefix]: v.content}), {}),
  correctAnswer: "?",
})));

【讨论】:

  • 先生,你能不能让它像从 php json_array 到 java var 一样动态。非常感谢。
  • 在我的脚本中我添加了你用这个给出的代码...
猜你喜欢
  • 2012-12-09
  • 1970-01-01
  • 1970-01-01
  • 2017-03-29
  • 2012-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-25
相关资源
最近更新 更多