Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Firestore REST API response to normal json?

I am trying to use Firestore from Unity by using REST API of it. Everything is working as expected till now.

When reading document from Firestore, it returns json in different format. Like this.

{
          "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"
}

How can I convert this kind of json to a normal json like this.

{
  "health":1008,
  "name":"Bhavin Panara",
  "birthday" : "1992-10-08T04:40:10Z",
  "alive":true,
  "floatingPointNumber":100.1
}
like image 817
Bhavin Panara Avatar asked Oct 23 '25 14:10

Bhavin Panara


1 Answers

I used the code from 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;
};
like image 183
joseluismurillorios Avatar answered Oct 25 '25 10:10

joseluismurillorios



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!