From 2352972eb58c54ab964bee1fed22598621b1a44a Mon Sep 17 00:00:00 2001 From: Ritesh Kumar Date: Tue, 5 Sep 2017 02:19:10 +0530 Subject: [PATCH] Add @mholt as a contributor --- .all-contributorsrc | 9 ++ components/ConversionPanel.js | 1 + package.json | 2 +- pages/json-to-flow-types.js | 1 + pages/json-to-go.js | 28 +++++ pages/json-to-ts-interface.js | 1 + utils/dummy-json.js | 1 + utils/json-to-go.js | 215 ++++++++++++++++++++++++++++++++++ utils/routes.js | 9 ++ yarn.lock | 6 +- 10 files changed, 269 insertions(+), 4 deletions(-) create mode 100644 pages/json-to-go.js create mode 100644 utils/json-to-go.js diff --git a/.all-contributorsrc b/.all-contributorsrc index 4e9ff79..d98457a 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -82,6 +82,15 @@ "contributions": [ "code" ] + }, + { + "login": "mholt", + "name": "Matt Holt", + "avatar_url": "https://avatars2.githubusercontent.com/u/1128849?v=4", + "profile": "https://matt.life", + "contributions": [ + "code" + ] } ] } diff --git a/components/ConversionPanel.js b/components/ConversionPanel.js index d519f80..f86e483 100644 --- a/components/ConversionPanel.js +++ b/components/ConversionPanel.js @@ -20,6 +20,7 @@ if (isBrowser) { require("codemirror/mode/rust/rust"); require("codemirror/mode/sql/sql"); require("codemirror/mode/clike/clike"); + require("codemirror/mode/go/go"); } const prettifyMap = { diff --git a/package.json b/package.json index b183dae..d694b96 100644 --- a/package.json +++ b/package.json @@ -40,7 +40,7 @@ "stringify-object": "^3.2.0", "transform-css-to-js": "^0.1.1", "transform-graphql-type-annotations": "^0.1.1", - "transform-json-types": "^0.1.1", + "transform-json-types": "^0.2.1", "unfetch": "^3.0.0", "xml-js": "^1.4.1" }, diff --git a/pages/json-to-flow-types.js b/pages/json-to-flow-types.js index ba7dda3..bfc1ea1 100644 --- a/pages/json-to-flow-types.js +++ b/pages/json-to-flow-types.js @@ -20,6 +20,7 @@ export default class Json2Ts extends PureComponent { leftMode="json" rightMode="typescript" url={this.props.url} + prettifyRightPanel={false} /> ); diff --git a/pages/json-to-go.js b/pages/json-to-go.js new file mode 100644 index 0000000..6224496 --- /dev/null +++ b/pages/json-to-go.js @@ -0,0 +1,28 @@ +import React, { PureComponent } from "react"; +import dynamic from "next/dynamic"; +import Layout from "../components/Layout"; +import ConversionPanel from "../components/ConversionPanel"; +import defaultText from "../utils/dummy-json"; +import json2go from "../utils/json-to-go" + +export default class extends PureComponent { + getTransformedValue = code => json2go(code).go + + render() { + return ( + + + + ); + } +} \ No newline at end of file diff --git a/pages/json-to-ts-interface.js b/pages/json-to-ts-interface.js index bf9306d..6e58585 100644 --- a/pages/json-to-ts-interface.js +++ b/pages/json-to-ts-interface.js @@ -22,6 +22,7 @@ export default class Json2Ts extends PureComponent { leftMode="json" rightMode="typescript" url={this.props.url} + prettifyRightPanel={false} /> ); diff --git a/utils/dummy-json.js b/utils/dummy-json.js index 750a463..c2ffe3a 100644 --- a/utils/dummy-json.js +++ b/utils/dummy-json.js @@ -20,6 +20,7 @@ const x = `{ ] }, { + "optionalField": "hello", "_id": "5988946ef6090217857d7b0f", "latitude": 47.460772, "longitude": 85.95137, diff --git a/utils/json-to-go.js b/utils/json-to-go.js new file mode 100644 index 0000000..9b89df4 --- /dev/null +++ b/utils/json-to-go.js @@ -0,0 +1,215 @@ +/* + JSON-to-Go + by Matt Holt + + https://github.com/mholt/json-to-go + + A simple utility to translate JSON into a Go type definition. +*/ + +function jsonToGo (json, typename) { + let data + let scope + let go = '' + let tabs = 0 + + try { + data = JSON.parse(json.replace(/\.0/g, '.1')) // hack that forces floats to stay as floats + scope = data + } + catch (e) { + return { + go: '', + error: e.message + } + } + + typename = format(typename || 'AutoGenerated') + append('type ' + typename + ' ') + + parseScope(scope) + + return {go: go} + + function parseScope (scope) { + let keyname + if (typeof scope === 'object' && scope !== null) { + if (Array.isArray(scope)) { + let i + let sliceType, scopeLength = scope.length + + for (i = 0; i < scopeLength; i++) { + const thisType = goType(scope[i]) + if (!sliceType) + sliceType = thisType + else if (sliceType !== thisType) { + sliceType = mostSpecificPossibleGoType(thisType, sliceType) + if (sliceType === 'interface{}') + break + } + } + + append('[]') + if (sliceType === 'struct') { + let k + let keys + const allFields = {} + + // for each field counts how many times appears + for (i = 0; i < scopeLength; i++) { + keys = Object.keys(scope[i]) + for (k in keys) { + keyname = keys[k] + if (!(keyname in allFields)) { + allFields[keyname] = { + value: scope[i][keyname], + count: 0 + } + } + + allFields[keyname].count++ + } + } + + // create a common struct with all fields found in the current array + // omitempty dict indicates if a field is optional + keys = Object.keys(allFields) + let struct = {}, omitempty = {} + for (k in keys) { + keyname = keys[k] + let elem = allFields[keyname] + + struct[keyname] = elem.value + omitempty[keyname] = elem.count !== scopeLength + } + + parseStruct(struct, omitempty) // finally parse the struct !! + } + else if (sliceType === 'slice') { + parseScope(scope[0]) + } + else + append(sliceType || 'interface{}') + } + else { + parseStruct(scope) + } + } + else + append(goType(scope)) + } + + function parseStruct (scope, omitempty) { + append('struct {\n') + ++tabs + const keys = Object.keys(scope) + for (const i in keys) { + const keyname = keys[i] + indent(tabs) + append(format(keyname) + ' ') + parseScope(scope[keyname]) + + append(' `json:"' + keyname) + if (omitempty && omitempty[keyname] === true) { + append(',omitempty') + } + append('"`\n') + } + indent(--tabs) + append('}') + } + + function indent (tabs) { + for (let i = 0; i < tabs; i++) + go += '\t'; + } + + function append (str) { + go += str + } + + // Sanitizes and formats a string to make an appropriate identifier in Go + function format (str) { + if (!str) + return '' + else if (str.match(/^\d+$/)) + str = 'Num' + str + else if (str.charAt(0).match(/\d/)) { + const numbers = { + '0': 'Zero_', '1': 'One_', '2': 'Two_', '3': 'Three_', + '4': 'Four_', '5': 'Five_', '6': 'Six_', '7': 'Seven_', + '8': 'Eight_', '9': 'Nine_' + } + str = numbers[str.charAt(0)] + str.substr(1) + } + return toProperCase(str).replace(/[^a-z0-9]/ig, '') || 'NAMING_FAILED' + } + + // Determines the most appropriate Go type + function goType (val) { + if (val === null) + return 'interface{}' + + switch (typeof val) { + case 'string': + if (/\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(\+\d\d:\d\d|Z)/.test(val)) + return 'time.Time' + else + return 'string' + case 'number': + if (val % 1 === 0) { + if (val > -2147483648 && val < 2147483647) + return 'int' + else + return 'int64' + } + else + return 'float64' + case 'boolean': + return 'bool' + case 'object': + if (Array.isArray(val)) + return 'slice' + return 'struct' + default: + return 'interface{}' + } + } + + // Given two types, returns the more specific of the two + function mostSpecificPossibleGoType (typ1, typ2) { + if (typ1.substr(0, 5) === 'float' + && typ2.substr(0, 3) === 'int') + return typ1 + else if (typ1.substr(0, 3) === 'int' + && typ2.substr(0, 5) === 'float') + return typ1 + else + return 'interface{}' + } + + // Proper cases a string according to Go conventions + function toProperCase (str) { + // https://github.com/golang/lint/blob/39d15d55e9777df34cdffde4f406ab27fd2e60c0/lint.go#L695-L731 + const commonInitialisms = [ + 'API', 'ASCII', 'CPU', 'CSS', 'DNS', 'EOF', 'GUID', 'HTML', 'HTTP', + 'HTTPS', 'ID', 'IP', 'JSON', 'LHS', 'QPS', 'RAM', 'RHS', 'RPC', 'SLA', + 'SMTP', 'SSH', 'TCP', 'TLS', 'TTL', 'UDP', 'UI', 'UID', 'UUID', 'URI', + 'URL', 'UTF8', 'VM', 'XML', 'XSRF', 'XSS' + ] + + return str.replace(/(^|[^a-zA-Z])([a-z]+)/g, function (unused, sep, frag) { + if (commonInitialisms.indexOf(frag.toUpperCase()) >= 0) + return sep + frag.toUpperCase() + else + return sep + frag[0].toUpperCase() + frag.substr(1).toLowerCase() + }).replace(/([A-Z])([a-z]+)/g, function (unused, sep, frag) { + if (commonInitialisms.indexOf(sep + frag.toUpperCase()) >= 0) + return (sep + frag).toUpperCase() + else + return sep + frag + }) + } +} + +module.exports = jsonToGo \ No newline at end of file diff --git a/utils/routes.js b/utils/routes.js index eb3b8e9..a533a82 100644 --- a/utils/routes.js +++ b/utils/routes.js @@ -148,6 +148,15 @@ export const categorizedRoutes = [ } ] }, + { + category: "Go", + iconName: "icon-go", + content: [{ + label: "JSON to Go Struct", + path: "/json-to-go", + desc: "An online REPL to generate Go Struct from JSON." + }] + }, { category: "XML", iconName: "icon-html", diff --git a/yarn.lock b/yarn.lock index 666f623..47167ec 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5270,9 +5270,9 @@ transform-graphql-type-annotations@^0.1.1: apollo-codegen "0.17.0-alpha.1" graphql "^0.10.5" -transform-json-types@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/transform-json-types/-/transform-json-types-0.1.1.tgz#d3b5ae620e9ba6e110f2ee7092f666e6b7d38683" +transform-json-types@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/transform-json-types/-/transform-json-types-0.2.1.tgz#54251813ba00f0d91689e42d53774393c51c462e" dependencies: lodash "^4.17.4" sha1 "^1.1.1"