botlib/proto_to_json.js (35 lines of code) (raw):
/**
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Utilities for converting from goog.protobuf.Struct proto to
* JSON.
*/
const JSON_SIMPLE_VALUE_KINDS =
new Set(['numberValue', 'stringValue', 'boolValue']);
function structProtoToJson(proto) {
if (!proto || !proto.fields) {
return {};
}
const json = {};
for (const field in proto.fields) {
json[field] = valueProtoToJson(proto.fields[field]);
}
return json;
}
function valueProtoToJson(proto) {
if (!proto || !proto.kind) {
return null;
}
if (JSON_SIMPLE_VALUE_KINDS.has(proto.kind)) {
return proto[proto.kind];
} else if (proto.kind === 'nullValue') {
return null;
} else if (proto.kind === 'listValue') {
if (!proto.listValue || !proto.listValue.values) {
console.warn('Invalid JSON list value proto: ', JSON.stringify(proto));
}
return proto.listValue.values.map(valueProtoToJson);
} else if (proto.kind === 'structValue') {
return structProtoToJson(proto.structValue);
} else {
console.warn('Unsupported JSON value proto kind: ', proto.kind);
return null;
}
}
module.exports = {
structProtoToJson
};