json - 如何将 Firestore REST API 响应转换为普通 json?
问题描述
我正在尝试通过使用它的 REST API 来使用 Unity 的 Firestore。到目前为止,一切都按预期工作。
从 Firestore 读取文档时,它返回不同格式的 json。像这样。
{
"name": "projects/firestore-unity-demo-87998/databases/(default)/documents/test/panara",
"fields": {
"health": {
"integerValue": "1008"
},
"name": {
"stringValue": "Bhavin Panara"
},
"birthday": {
"timestampValue": "1992-10-08T04:40:10Z"
},
"alive": {
"booleanValue": true
},
"floatingPointNumber": {
"testFloat": 100.1
}
},
"createTime": "2019-07-30T13:27:09.599079Z",
"updateTime": "2019-07-31T11:41:10.637712Z"
}
如何将这种 json 转换为像这样的普通 json。
{
"health":1008,
"name":"Bhavin Panara",
"birthday" : "1992-10-08T04:40:10Z",
"alive":true,
"floatingPointNumber":100.1
}
解决方案
const getFireStoreProp = (value) => {
const props = {
arrayValue: 1,
bytesValue: 1,
booleanValue: 1,
doubleValue: 1,
geoPointValue: 1,
integerValue: 1,
mapValue: 1,
nullValue: 1,
referenceValue: 1,
stringValue: 1,
timestampValue: 1,
};
return Object.keys(value).find(k => props[k] === 1);
};
export const fireStoreParser = (value) => {
let newVal = value;
// You can use this part to avoid mutating original values
// let newVal;
// if (typeof value === 'object') {
// newVal = { ...value };
// } else if (value instanceof Array) {
// newVal = value.slice(0);
// } else {
// newVal = value;
// }
const prop = getFireStoreProp(newVal);
if (prop === 'doubleValue' || prop === 'integerValue') {
newVal = Number(newVal[prop]);
} else if (prop === 'arrayValue') {
newVal = ((newVal[prop] && newVal[prop].values) || []).map(v => fireStoreParser(v));
} else if (prop === 'mapValue') {
newVal = fireStoreParser((newVal[prop] && newVal[prop].fields) || {});
} else if (prop === 'geoPointValue') {
newVal = { latitude: 0, longitude: 0, ...newVal[prop] };
} else if (prop) {
newVal = newVal[prop];
} else if (typeof newVal === 'object') {
Object.keys(newVal).forEach((k) => { newVal[k] = fireStoreParser(newVal[k]); });
}
return newVal;
};
推荐阅读
- git - 无法从 git 授权 github
- computer-science - 比较两个二叉堆是否相等的最著名的界限是什么?
- apache-kafka - Kafka RoundRobin 分区程序未将消息分发到所有分区
- sql - 我应该如何将 URL 添加到我的 SQL 案例语句中?
- rust - 硬件计时器在首次使用时立即完成。STM32F303VC
- python - 如何在 Python 3 中更改具有特定坐标的像素颜色 | 开放式简历?
- pushviewcontroller - 如何将动作从 SKScene 组件传播到 UIViewController
- python - 如何将数据从服务器发送到所有连接的客户端?
- python - 具有没有简单表达式的约束的 Scipy 最小化
- python - 检测错误编码的 UTF-8 文本文件中的编码