【问题标题】:How can I parse through local JSON file in React js?如何在 React js 中解析本地 JSON 文件?
【发布时间】:2016-10-05 14:30:52
【问题描述】:

如何解析 JSON 文件以检索其所有数据并在我的代码中使用它?

我已尝试导入文件并尝试控制台记录它,但它所做的只是打印 Object {}:

import jsonData from "./file.json";
console.log(jsonData);

这就是我的 file.json 的样子:

[
    {
      "id": 1,
      "gender": "Female",
      "first_name": "Helen",
      "last_name": "Nguyen",
      "email": "hnguyen0@bloomberg.com",
      "ip_address": "227.211.25.18"
    }, {
      "id": 2,
      "gender": "Male",
      "first_name": "Carlos",
      "last_name": "Fowler",
      "email": "cfowler1@gnu.org",
      "ip_address": "214.248.201.11"
    }
]

我希望能够访问每个组件的名字和姓氏并将其打印在网站上。

【问题讨论】:

  • 这似乎对我有用

标签: javascript json reactjs


【解决方案1】:
var data = require('../../file.json'); // forward slashes will depend on the file location

var data = [
    {
      "id": 1,
      "gender": "Female",
      "first_name": "Helen",
      "last_name": "Nguyen",
      "email": "hnguyen0@bloomberg.com",
      "ip_address": "227.211.25.18"
    }, {
      "id": 2,
      "gender": "Male",
      "first_name": "Carlos",
      "last_name": "Fowler",
      "email": "cfowler1@gnu.org",
      "ip_address": "214.248.201.11"
    }
];

for (var i = 0; i < data.length; i++)
{
    var obj = data[i];
    console.log(`Name: ${obj.last_name}, ${obj.first_name}`);
}

https://jsfiddle.net/c9wupvo6/

【讨论】:

  • 我收到此错误:Uncaught Error: Cannot find module "json!./Sections/file.json" 即使这是正确的路径。
【解决方案2】:

我在取回一个空对象时也遇到了问题。即使按照上面的建议使用require

fetch 但是解决了我的问题:

fetch('./data/fakeData.json')
  .then((res) => res.json())
  .then((data) => {
    console.log('data:', data);
  })

(截至今天,支持不是最佳的:http://caniuse.com/#feat=fetch

【讨论】:

  • 这似乎应该可行。但是每当我尝试它时,我都会得到“localhost/:1 Uncaught (in promise) SyntaxError: Unexpected token
  • 如何进行这项工作?为 fetch 生成的 url 不正确。因此 jseals。错误。
  • @Community 我找到了解决方案!您需要传递完整路径(在项目内部),而不是传递相对路径,例如 fetch("src/data/fakeData.json)。不要使用res.json(),而是使用res.text(),最后使用JSON.parse(data)
【解决方案3】:

使用 webpack 2.0.0+ 打包的应用程序(例如使用 create-react-app 创建的应用程序)支持从 json 导入,与问题中完全相同(请参阅 this answer

请注意import 会缓存结果,即使该结果已解析为 json,因此如果您修改该对象,其他导入它的模块也会引用 同一对象,而不是新解析的副本。

要获得“干净”的副本,您可以创建一个克隆它的函数,例如:

import jsonData from './file.json';

const loadData = () => JSON.parse(JSON.stringify(jsonData));

或者,如果您使用的是lodash

import jsonData from './file.json';
import { cloneDeep } from 'lodash';

const loadData = () => cloneDeep(jsonData);

【讨论】:

    【解决方案4】:

    对于那些也有这个问题的人,这段代码似乎已经解决了这个问题

    var jsonData = require('../../file.json');
    
    class blah extends React.Component {
    
    render(){
        var data; 
    
        function loadJSON(jsonfile, callback) {   
    
            var jsonObj = new XMLHttpRequest();
            jsonObj.overrideMimeType("application/json");
            jsonObj.open('GET', "../../file.json", true);
            jsonObj.onreadystatechange = function () {
                  if (jsonObj.readyState == 4 && jsonObj.status == "200") {
                    callback(jsonObj.responseText);
                  }
            };
            jsonObj.send(null);  
         }
    
        function load() {
    
            loadJSON(jsonData, function(response) {
                data = JSON.parse(response);
                console.log(data);
            });
        }
    
        load();
    }
    
    }
    

    【讨论】:

    • 这对于将 JSON 导入本地 JS 代码来说似乎太过分了,难道没有更简单的解决方案吗?
    【解决方案5】:

    JS 扩展运算符还有助于获取对象的深层副本。

    import jsonData from '../../file.json';
    
    const loadData = [...jsonData];
    

    【讨论】:

    • 展开操作符是浅拷贝,而不是深拷贝。以上将产生一个新数组,但其中的对象实例完全相同。
    • @EricHaynes 是对的
    猜你喜欢
    • 1970-01-01
    • 2012-08-22
    • 2019-01-25
    • 2019-06-03
    • 2017-12-23
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多