在HTML div中显示JSON响应的最佳方法是什么?

时间:2018-04-21 21:04:28

标签: html json

我有一个返回以下JSON响应的URL(适用于多家餐馆)。解析响应并在HTML页面中显示单个字段的最简单方法是什么?

[
  {
    restaurant_name: 'R_name',
    address: {
      longitude: -121.483693,
      city: 'City Name',
      zip: '00000',
      latitude: 317.328255,
      state: 'ZZ',
      street_address: 'Street Address',
    },
    menu_data: [
      'Zereshk',
      'Khoreshe Ghorm-E-Sabszi with Beef',
      'Khoreshe Gheym-Budemjan with Beef',
      'Khoreshe Gheym with Beef',
      'Khoreshe Fesenjan with Breast Chicken',
      'Khoreshe Karafs with Beef',
      'Boneless Jujeh Kabob (Chicken)',
      'Kobedeh Kabob (Ground Beef)',
      'Potato Salad with Chicken',
      'Salad Olvieh with Lavash',
      'Kashk-E-Budemjan(Egg Plant Dip)',
      'Grilled Eggplant with Nuts',
      'Grape Leaf Stuffed with Our Special Vegetable and Rice and Fresh Herbs',
      'Koukou Sabzi (Mediterranean Quiche)',
      'Hummus',
      'Babaghanouge',
      'Cucumber Yogurt Mix',
      'Shallot Yogurt Mix',
    ],
  },
];

2 个答案:

答案 0 :(得分:0)

有一个谷歌浏览器扩展JSON格式化程序here,可用于显示用户友好的json。你是在打扰json调试purpurse吗?

答案 1 :(得分:0)

以下是如何解决这个问题。您已经获得了JSON格式的响应,现在您只需要遍历密钥并从中创建模板字符串,然后再创建一个html。提供最基本的方法:

您可以使用Object.keys()(ref:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)从对象中获取键数组。现在,您可以遍历这些键,附加值并创建模板字符串/文字(ref:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)。然后你可以添加这个元素作为你已经拥有的一些div的内部html。 现在这是最基本的方法。显然,您可以优化步骤数。