使用 normalizr 规范化我的嵌套 JSON
Normalizing my nested JSON with normalizr
我的服务有以下 JSON:
[
{
"name":"Voter1",
"id":1,
"votingCard":{
"verificationCodes":[
"3I08jA",
"3x0eyE",
"2_i69I"
],
"votingCode":"7zCOelDnjfBm7TtFydc4QodgonG",
"finalizationCode":"jyYu",
"confirmationCode":"4ACfcpBVH45iAXqg7hJ0tbEe_tV"
}
},
.....
{
"id":5,
"name":"Voter5",
"votingCard":{
"verificationCodes":[
"2c9I9a",
"3bEeEa",
"1gPKx2"
],
"confirmationCode":"4Z7wNG35VR2UMO6-W-0aZVEhbLM",
"votingCode":"6YQ2x-c8LXJZF05gh3zTajU79ct",
"finalizationCode":"S0CY"
}
}
]
并希望将其规范化,因此有一个投票卡列表和一个 "votingCard" 属性 通过 ID 引用投票卡的选民列表。
import { normalize, schema } from 'normalizr';
const votingCard = new schema.Entity('votingCard');
const voter = new schema.Entity('voter', {
votingCard: votingCard,
});
const votersSchema = new schema.Array(voter);
const mutations = {
SOCKET_SYNCVOTERS: (state, data) => {
var input = JSON.parse(data);
const normalizedData = normalize(input, votersSchema);
console.log(normalizedData);
},
};
但是,我没有得到我想要的:
为什么会有"undefined"?
我认为您需要在 votingCard 实体的选项中指定一个“idAttribute”——问题是 normalizr 在这些对象中找不到“id”字段,所以它们都被拾取为 id undefined并在实体中相互覆盖。参见:https://github.com/paularmstrong/normalizr/blob/master/docs/api.md#schema
我的服务有以下 JSON:
[
{
"name":"Voter1",
"id":1,
"votingCard":{
"verificationCodes":[
"3I08jA",
"3x0eyE",
"2_i69I"
],
"votingCode":"7zCOelDnjfBm7TtFydc4QodgonG",
"finalizationCode":"jyYu",
"confirmationCode":"4ACfcpBVH45iAXqg7hJ0tbEe_tV"
}
},
.....
{
"id":5,
"name":"Voter5",
"votingCard":{
"verificationCodes":[
"2c9I9a",
"3bEeEa",
"1gPKx2"
],
"confirmationCode":"4Z7wNG35VR2UMO6-W-0aZVEhbLM",
"votingCode":"6YQ2x-c8LXJZF05gh3zTajU79ct",
"finalizationCode":"S0CY"
}
}
]
并希望将其规范化,因此有一个投票卡列表和一个 "votingCard" 属性 通过 ID 引用投票卡的选民列表。
import { normalize, schema } from 'normalizr';
const votingCard = new schema.Entity('votingCard');
const voter = new schema.Entity('voter', {
votingCard: votingCard,
});
const votersSchema = new schema.Array(voter);
const mutations = {
SOCKET_SYNCVOTERS: (state, data) => {
var input = JSON.parse(data);
const normalizedData = normalize(input, votersSchema);
console.log(normalizedData);
},
};
但是,我没有得到我想要的:
为什么会有"undefined"?
我认为您需要在 votingCard 实体的选项中指定一个“idAttribute”——问题是 normalizr 在这些对象中找不到“id”字段,所以它们都被拾取为 id undefined并在实体中相互覆盖。参见:https://github.com/paularmstrong/normalizr/blob/master/docs/api.md#schema