错误 SyntaxError: JSON.parse: JSON 数据的第 1 行第 1 列有意外字符。

huangapple go评论96阅读模式
英文:

Error SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

问题

我正在创建一个用户管理系统,需要从本地的 JSON 文件中筛选用户。问题是我无法获取 JSON 文件,控制台显示以下错误:

Error SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

JSON 文件位于 src/data/data.json 中,UserList.jsx 位于 src/components/UserListstore.js 位于 src/store/store/your textjs

以下是 UserList.jsx,在此文件中尝试获取 JSON 数据,但数据未显示在页面上:

import React, { useEffect , useState} from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { setUsers } from '../store/store'
import UserCard from './UserCard'
import Pagination from './Pagination'

const UserList = () => {
    const dispatch = useDispatch();
    const users = useSelector((state) => state.users.users)
    const [currentPage, setCurrentPage] = useState(1);
    const usersPerPage = 20;

    useEffect(() => {
        fetch('../data/heliverse_mock_data.json')
            .then((res) => res.json())
            .then((jsonData) => {
                dispatch(setUsers(jsonData))
            })
            .catch((err) => {
                console.error('Error', err)
            })
    }, [dispatch])

    const handlePageChange = (pageNumber) => {
        setCurrentPage(pageNumber)
    }

    const indexOfLastUser = currentPage * usersPerPage
    const indexOfFirstUser = indexOfLastUser - usersPerPage
    const currentUsers = users.slice(indexOfFirstUser, indexOfLastUser)
    const totalPages = Math.ceil(users.length / usersPerPage)

    return (
        <div className=' grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 mt-8'>

            {currentUsers.map((user) => (
                <UserCard key={user.id} user={user} />
            ))}
            <Pagination totalPages={totalPages} onPageChange={handlePageChange}/>
        </div>
    )
}

export default UserList

这是 store.js 文件,使用 Redux Toolkit 进行状态管理:

import { configureStore, createSlice } from '@reduxjs/toolkit';

const initialState = {
    users: [],
    searchQuery: '',
    domainFilter: '',
    genderFilter: '',
    availabilityFilter: '',
    paginationPage: 1,
    teamMembers: [],
    totalPages: 0
};

const userSlice = createSlice({
    name: 'users',
    initialState,
    reducers: {
        setUsers: (state, action) => {
            state.users = action.payload;
        },
        setSearchQuery: (state, action) => {
            state.searchQuery = action.payload
        },
        setDomainFilter: (state, action) => {
            state.domainFilter = action.payload
        },
        setGenderFilter: (state, action) => {
            state.genderFilter = action.payload;
        },
        setAvailabilityFilter: (state, action) => {
            state.availabilityFilter = action.payload
        },
        setPaginationPage: (state, action) => {
            state.paginationPage = action.payload
        },
        addToTeam: (state, action) => {
            state.teamMembers.push(action.payload)
        },
        removeFromTeam: (state, action) => {
            state.teamMembers = state.teamMembers.filter(
                (user) => user.id !== action.payload
            )
        }
    }
})

const store = configureStore({
    reducer: {
        users: userSlice.reducer
    },
});

export const { setUsers, setSearchQuery, setDomainFilter, setGenderFilter, setAvailabilityFilter, setPaginationPage , addToTeam , removeFromTeam} = userSlice.actions

export default store;

您已经尝试验证 JSON 文件,认为可能是 JSON 文件损坏,但这似乎不是问题的原因。可能的原因之一是 fetch() 中的文件位置路径不正确。

英文:

Im making a User Management System where I need to filter the user from a json file, which I have locally. The problem is I can't fetch the json file and I get this error in console:
Error SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

The json is located in src/data/data.json
Userlist.jsx is located in src/components/UserList
store.js is located in src/store/store/your textjs

This is the UserList.jsx,where the json is fetched but the data isn't showing on the Page:

import React, { useEffect , useState} from &#39;react&#39;
import { useDispatch,useSelector } from &#39;react-redux&#39;
import { setUsers } from &#39;../store/store&#39;
import UserCard from &#39;./UserCard&#39;
import Pagination from &#39;./Pagination&#39;
const UserList = () =&gt; {
const dispatch = useDispatch();
const users = useSelector((state) =&gt; state.users.users)
const [currentPage, setCurrentPage] = useState(1);
const usersPerPage = 20;
useEffect(() =&gt; {
fetch(&#39;../data/heliverse_mock_data.json&#39;)
.then((res) =&gt; res.json())
.then((jsonData) =&gt; {
dispatch(setUsers(jsonData))
})
.catch((err) =&gt; {
console.error(&#39;Error&#39;, err)
})
}, [dispatch])
const handlePageChange = (pageNumber)=&gt;{
setCurrentPage(pageNumber)
}
const indexOfLastUser = currentPage * usersPerPage
const indexOfFirstUser = indexOfLastUser - usersPerPage
const currentUsers = users.slice(indexOfFirstUser, indexOfLastUser)
const totalPages = Math.ceil(users.length / usersPerPage)
return (
&lt;div className=&#39; grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 mt-8&#39;&gt;
{currentUsers.map((user) =&gt; (
&lt;UserCard key={user.id} user={user} /&gt;
))}
&lt;Pagination totalPages={totalPages} onPageChange={handlePageChange}/&gt;
&lt;/div&gt;
)
}
export default UserList

This is store.js of redux-toolkit:

import { configureStore, createSlice } from &#39;@reduxjs/toolkit&#39;;
const initialState = {
users: [],
searchQuery: &#39;&#39;,
domainFilter: &#39;&#39;,
genderFilter: &#39;&#39;,
availabilityFilter: &#39;&#39;,
paginationPage: 1,
teamMembers: [],
totalPages: 0
};
const userSlice = createSlice({
name: &#39;users&#39;,
initialState,
reducers: {
setUsers: (state, action) =&gt; {
state.users = action.payload;
},
setSearchQuery: (state, action) =&gt; {
state.searchQuery = action.payload
},
setDomainFilter: (state, action) =&gt; {
state.domainFilter = action.payload
},
setGenderFilter: (state, action) =&gt; {
state.genderFilter = action.payload;
},
setAvailabilityFilter: (state, action) =&gt; {
state.availabilityFilter = action.payload
},
setPaginationPage: (state, action) =&gt; {
state.paginationPage = action.payload
},
addToTeam: (state, action) =&gt; {
state.teamMembers.push(action.payload)
},
removeFromTeam: (state, action) =&gt; {
state.teamMembers = state.teamMembers.filter(
(user) =&gt; user.id !== action.payload
)
}
}
})
const store = configureStore({
reducer: {
users: userSlice.reducer
},
});
export const { setUsers, setSearchQuery, setDomainFilter, setGenderFilter, setAvailabilityFilter, setPaginationPage , addToTeam , removeFromTeam} = userSlice.actions
export default store;

I tried validating the json file thinking maybe the json file might be corrupted but this isn't the case. I might be thinking maybe the file location directory in fetch() is wrong in my code .

答案1

得分: 3

从你提到的情况来看,似乎与浏览器在使用 fetch 时处理本地文件路径可能存在一些问题。虽然 fetch 主要用于管理 HTTP 请求,而不是加速连接速度,但在尝试访问本地文件(如 JSON 文件)时,我们仍然应该找到解决这些问题的方法。确实,我们已经找到了解决方法!

为了避免在使用像 create react app 并从本地目录获取数据时出现的任何复杂情况(不穷尽),尝试像下面示例中所示直接将 JSON 数据导入到 React 组件中:

我的代码:

import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { setUsers } from '../store/store'
import UserCard from './UserCard'
import Pagination from './Pagination'
import myData from '../data/heliverse_mock_data.json' // 直接在这里导入你的 JSON 数据

const UserList = () => {
    // ...
    useEffect(() => {
        dispatch(setUsers(myData)) // 直接使用数据
    }, [dispatch])
    // ...
}

export default UserList

使用 WebpackJSON 加载器功能,可以将 JSON 数据直接导入到你的代码中作为 JavaScript 对象。重要的是要记住,较大的 JSON 文件可能会影响应用程序的性能,因为它们会增加由 Webpack 创建的 JavaScript bundle 的大小。

最后,请记住文件路径必须相对于导入它们的文件。所以,如果你的结构类似于:

src
    data
        heliverse_mock_data.json
    components
        UserList.jsx

要正确做到这一点,请确保你提供的引用是相对于文件在你的应用程序目录结构中所在位置的。假设一切都正确完成,你的 heliverse_mock_data.json 文件中没有损坏或格式错误的问题,那么这个更改应该可以正常工作,没有任何问题。愉快的编码!

英文:

From what you've mentioned it seems like there might be some issues related to how the browser handles local file paths when using fetch. While fetch specializes in managing HTTP requests rather than accelerating connection speeds when attempting access into local files such as JSON files we should still find ways to resolve these setbacks. And indeed we have!

To sidestep any complications that arise while working with something like create react app and fetching from local directories (in-exhaustive) try importing the JSON data straight away into the React component as shown below:

My Code:

import React, { useEffect , useState} from &#39;react&#39;
import { useDispatch, useSelector } from &#39;react-redux&#39;
import { setUsers } from &#39;../store/store&#39;
import UserCard from &#39;./UserCard&#39;
import Pagination from &#39;./Pagination&#39;
import myData from &#39;../data/heliverse_mock_data.json&#39; // Import your JSON data right there
const UserList = () =&gt; {
// ...
useEffect(() =&gt; {
dispatch(setUsers(myData)) // Use the data straight away
}, [dispatch])
// ...
}
export default UserList

Using Webpacks JSON loader feature, it is possible to import JSON data as a JavaScript object directly into your code. It is important to keep in mind that larger JSON files may impact your applications performance as they will increase the size of your JavaScript bundle created by Webpack.

Just as a final check, remember that file paths need to be relative to the file where you're importing them. So if you have a structure like:

src
data
heliverse_mock_data.json
components
UserList.jsx

To do so correctly. Make sure that the reference you provide is relative to where the file being imported is located within your application directory structure. Assuming everything else has been done correctly and there are no issues with corruption or formatting errors in your heliverse_mock_data.json file specifically this change should work without any problems. Happy coding!

huangapple
  • 本文由 发表于 2023年6月22日 01:13:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525687.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定