首页 > 解决方案 > 如何将 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
}

标签: jsonfirebasegoogle-cloud-firestorejson.net

解决方案


我使用了firestore-parser的代码


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;
};

推荐阅读