Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support json with comments #4

Closed
unional opened this issue Feb 14, 2017 · 19 comments
Closed

Support json with comments #4

unional opened this issue Feb 14, 2017 · 19 comments
Assignees

Comments

@unional
Copy link

unional commented Feb 14, 2017

Currently, if there are comments in json, this extension will format it incorrectly. Some properties double-quote will be gone.

It is true that JSON should not have comments on it by specification, but it would be good to support it.

For example, .eslintrc.json do support comments, also tslint.json

@richie5um
Copy link
Owner

Thank you for raising this issue.

This extension converts to the selected text to JSON, and then sorts as it serialises it back. As such, sorting JSON that includes comments is a problem. I'll investigate to see if there is an alternative solution, but, I suspect there won't be.

@richie5um
Copy link
Owner

Thanks. I was hoping I might be able to to retain the comments - but, this'll do as a great solution for now. Many thanks.

@richie5um richie5um self-assigned this Feb 14, 2017
@unional
Copy link
Author

unional commented Feb 14, 2017

You are right that the code I linked to does not retain comments.
One way to get around it is to do it two passes:
When stripping the comments, record their location related to the JSON key/value.
Then after parse->stringify Find the JSON key/value index and inject the comments back in.

Just a thought.

@nonoroazoro
Copy link

@richie5um I used node-jsonc-parser in my VSCode extension to manipulate JSON with comments, maybe it will help.

@richie5um
Copy link
Owner

Thanks. Will take a look.

@jaymegordo
Copy link

+1 for this, I always have comments in settings files, would love it if they could be preserved!

@GBrachetta
Copy link

Definitely +1 this. I have a big VSCode settings.json with comments (ca 700 lines) and would love to be able to sort it and keep the comments.
I believe it's a common scenario to use the extension.

@richie5um
Copy link
Owner

I would love to be able to get this working, but every time I look at it I come across two problems; I can't seem to solve it when comments need to stay relative to their position (i.e. no point keeping the comment in the same place, if the property it was relevant to has moved position), I can't seem to find the time to spend more time on it :).

@GBrachetta
Copy link

I understand. I wonder if comments could be transformed as dummy key-value pairs during the parsing process and transformed back after sorting. Well, maybe that's nonsense, just an idea :)

@richie5um
Copy link
Owner

richie5um commented Mar 20, 2021

... and, as if by magic, I think I may have found a solution. It's gonna take me some time to test/investigate, but, looks like it should work. :)

PS: I'd wondered the same, but wasn't sure how to reliably achieve that - definitely not a nonsense idea!! But, I think I've got a way forward :).

@GBrachetta
Copy link

Yay!!!

@richie5um
Copy link
Owner

It works......
image

@GBrachetta
Copy link

That's amazing, looking forward to the release! Thank you!! Finally settings.json easy to navigate! :)

@richie5um
Copy link
Owner

v1.20.0 is now published. Please let me know if you encounter issues. The new parser/outputter mechanism tries first, but it'll fallback to the old mechanisms.

@GBrachetta
Copy link

Great, I'll try it right away! Thank you!

@GBrachetta
Copy link

Woah, this seems to work like a charm! Fantastic job!

@richie5um
Copy link
Owner

Phew. Give me a shout if you see any issues.

I can now close this 4 year old issue :)))))

@matthewelmer
Copy link

matthewelmer commented Sep 22, 2023

This breaks when I attempt to run it on my VS Code's settings.json:

{
    "editor.minimap.enabled": false,
    "editor.rulers": [
        80,
        120
    ],
    "editor.wordWrapColumn": 120,
    "editor.detectIndentation": false,
    "explorer.confirmDragAndDrop": false,
    "explorer.confirmDelete": false,
    "files.exclude": {
        "**/.git": false,
        "**/.svn": false,
        "**/.hg": false,
        "**/CVS": false,
        "**/.DS_Store": false,
        "**/Thumbs.db": false
    },
    "files.associations": {
        "*.sm": "cpp",
        "*.json": "jsonc",
        "*.czml": "json",
        "fstab": "plaintext"
    },
    "git.enabled": true,
    "git.enableSmartCommit": false,
    "git.autofetch": true,
    // "rewrap.wrappingColumn": 80,  // unspecified for ruler interaction (alt-q)
    "[markdown]": {
        "editor.unicodeHighlight.ambiguousCharacters": false,
        "editor.unicodeHighlight.invisibleCharacters": false,
        "diffEditor.ignoreTrimWhitespace": false,
        "editor.wordWrap": "on",
        "editor.quickSuggestions": {
            "comments": "off",
            "strings": "off",
            "other": "off"
        },
        "cSpell.fixSpellingWithRenameProvider": true,
        "cSpell.advanced.feature.useReferenceProviderWithRename": true,
        "cSpell.advanced.feature.useReferenceProviderRemove": "/^#+\\s/",
        "rewrap.autoWrap.enabled": false,
        "editor.wrappingIndent": "indent",
        "editor.rulers": []
    },
    "[plaintext]": {
        "editor.unicodeHighlight.ambiguousCharacters": false,
        "editor.unicodeHighlight.invisibleCharacters": false,
        "rewrap.autoWrap.enabled": false,
    },
    "rewrap.wholeComment": true,
    "rewrap.autoWrap.enabled": true,
    "terminal.integrated.defaultProfile.windows": "PowerShell",
    "todohighlight.keywords": [
        // use custom style
        {
            "text": "stuff I want red", // required; only serves as title
            "regex": {
                "pattern": "(?<=[ \\t\\r\\n\\v\\f])BUG:?|IMPORTANT:?|(?<=[ \\t\\r\\n\\v\\f])BAD:?|TERRIBLE:?"
            },
            "color": "#000000",
            "border": "1px solid #e73c3c",
            "borderRadius": "4px",
            "backgroundColor": "#e73c3c"
        },
        {
            "text": "stuff I want orange", // required; only serves as title
            "regex": {
                "pattern": "FIXME:?|TODO:?|GROSS:?|TESTME:?|SMELLY?:?"
            },
            "color": "#000000",
            "border": "1px solid #ff6600",
            "borderRadius": "4px",
            "backgroundColor": "#ff6600"
        },
        {
            "text": "stuff I want yellow", // required; only serves as title
            "regex": {
                "pattern": "FUTURE WORK:?|OPTIMIZEME:?"
            },
            "color": "#000000",
            "border": "1px solid #ffff00",
            "borderRadius": "4px",
            "backgroundColor": "#ffff00"
        },
        {
            "text": "stuff I want green", // required; only serves as title
            "regex": {
                "pattern": "UPDATEME:?|IDEA:?"
            },
            "color": "#000000",
            "border": "1px solid #2ecc71",
            "borderRadius": "4px",
            "backgroundColor": "#2ecc71"
        },
        {
            "text": "stuff I want blue", // required; only serves as title
            "regex": {
                "pattern": "NOTES?:?|added to UML:?"
            },
            "color": "#000000",
            "border": "1px solid #3498db",
            "borderRadius": "4px",
            "backgroundColor": "#3498db"
        },
        {
            "text": "stuff I want violet", // required; only serves as title
            "regex": {
                "pattern": "HACK:?|QUESTION:?|COMPATIBILITY:?|MAGIC NUMBER:?"
            },
            "color": "#000000",
            "border": "1px solid #9b59b6",
            "borderRadius": "4px",
            "backgroundColor": "#9b59b6"
        },
        // {
        //   "text": "xx",
        //   "color": "#ff595e"
        // },
        {
            "text": "x or xx then k",
            "regex": {
                "pattern": "(?:x|xx)(?=k)"
            },
            "color": "#ff595e"
        },
        {
            "text": "xz",
            "color": "#16db65"
        },
        // {
        //   "text": "zz",
        //   "color": "#1982c4"
        // },
        {
            "text": "z or zz then k",
            "regex": {
                "pattern": "(?:z|zz)(?=k)"
            },
            "color": "#1982c4"
        },
        // use default style (note: must come after custom styles)
        // {
        //   "text": " @something-UPPER_lower", // required; only serves as title
        //   "regex": {
        //     "pattern": "(?<=[ \\t\\r\\n\\v\\f])@[-_a-zA-Z]*"
        //   }
        // }
    ],
    "todohighlight.defaultStyle": {
        "color": "#569CD6",
        "border": "",
        "borderRadius": "",
        "backgroundColor": ""
    },
    "workbench.startupEditor": "none",
    "editor.foldingStrategy": "indentation",
    "explorer.sortOrderLexicographicOptions": "upper",
    "editor.foldingMaximumRegions": 3000,
    "C_Cpp.simplifyStructuredComments": false,
    "cSpell.userWords": [
        "Acta",
        "actaastro",
        "AEOE",
        "AEOESTATE",
        "Ambrosi",
        "apoapsis",
        "arange",
        "arccos",
        "asarray",
        "Astria",
        "Astronautica",
        "backronym",
        "bandlimited",
        "Basicality",
        "Beutler",
        "Blandino",
        "BLAS",
        "borderaxespad",
        "Bpqf",
        "Builtins",
        "CACI",
        "CARTESIANSTATE",
        "cartopy",
        "Catastrophizing",
        "CCFLAGS",
        "ccrs",
        "cesiumpy",
        "CFLAGS",
        "Cheatsheet",
        "Chebyshev",
        "CHECKFLAGS",
        "checkpointed",
        "chkpnt",
        "Clairaut",
        "coeffs",
        "Coherentism",
        "Compatibilism",
        "consts",
        "Costates",
        "cppcheck",
        "CPPFLAGS",
        "CSNR",
        "CSTAT",
        "CXXFLAGS",
        "CZML",
        "datamsg",
        "datapoint",
        "Dealbreakers",
        "defn",
        "Defund",
        "dejavuserif",
        "demars",
        "deque",
        "DNDEBUG",
        "Dormand",
        "Doxastic",
        "DRELEASE",
        "dtoi",
        "dtoszt",
        "DTRICK",
        "dtype",
        "ECEN",
        "ecgno",
        "Eigen",
        "eqns",
        "Eulerian",
        "Evgeny",
        "EXITONERROR",
        "extensionless",
        "Fehlberg",
        "figlabel",
        "figlabels",
        "fignum",
        "fignums",
        "figsize",
        "filecontents",
        "filemsg",
        "fontset",
        "fontsize",
        "fopenmp",
        "Foundationalism",
        "functionme",
        "Fxxxrz",
        "gashopper",
        "gluestick",
        "Gökalp",
        "Grossman",
        "hackiness",
        "Hohmann",
        "Idiosyncracies",
        "ifdef",
        "ifeq",
        "ifndef",
        "ifneq",
        "infile",
        "Interactionism",
        "interpoints",
        "inxi",
        "Iskender",
        "Jerred",
        "Kalman",
        "Katalenich",
        "Keplerian",
        "KEPLERIANSTATE",
        "Kikkoman",
        "Koepsell",
        "Koepsell's",
        "Kutta",
        "labmates",
        "lboost",
        "LDFLAGS",
        "libcow",
        "libdeps",
        "libdog",
        "linalg",
        "linestyle",
        "linewidth",
        "linspace",
        "loadmat",
        "Lobatto",
        "loglog",
        "logterp",
        "lumve",
        "LVLH",
        "Makefiles",
        "MAKEFLAGS",
        "mathtext",
        "Mathworks",
        "matplotlib",
        "memcheck",
        "Metaprogramming",
        "Michaël",
        "Milgram",
        "Molniya",
        "mticker",
        "multiset",
        "MVDES",
        "mxkm",
        "Mysim",
        "nalgebra",
        "ncol",
        "ncols",
        "ndarray",
        "NDEBUG",
        "nemo",
        "NEWCHANNEL",
        "Nichomachean",
        "njit",
        "nominalize",
        "nonconformal",
        "Noncopyable",
        "Nondimensionalized",
        "npoints",
        "NPROC",
        "numba",
        "omni",
        "OPTIMIZEME",
        "overengineered",
        "overspray",
        "Parameterizations",
        "pathfinding",
        "pdflatex",
        "periapsis",
        "Physicalist",
        "powf",
        "powi",
        "PRIMARYBODY",
        "prolly",
        "Protobuf",
        "pthread",
        "pthreads",
        "PTSD",
        "Pxxk",
        "Pxxkm",
        "Pxzk",
        "pyplot",
        "Pzzk",
        "Quang",
        "RAAN",
        "Raman",
        "rbar",
        "relerr",
        "relerror",
        "rgba",
        "Roadmap",
        "Runge",
        "rustaceans",
        "rustfmt",
        "Salomon",
        "Sambal",
        "sarlacc",
        "savefig",
        "scipy",
        "Semesterly",
        "semilogyterp",
        "semimajor",
        "Sercel",
        "setpoint",
        "Shafirovich",
        "shellcheck",
        "Solidworks",
        "spdlog",
        "stepsize",
        "struct",
        "Structs",
        "Stumpff",
        "subinterval",
        "subintervals",
        "subjectivities",
        "suptitle",
        "supxlabel",
        "supylabel",
        "symplectic",
        "Synergize",
        "TAMU",
        "tauri",
        "TESTME",
        "ticklabels",
        "timespan",
        "timestep",
        "Timesteps",
        "todohighlight",
        "Todoist",
        "traj",
        "typenum",
        "typst",
        "uchar",
        "UDUNITS",
        "ulong",
        "ulongint",
        "underweighting",
        "unelaborate",
        "unflatten",
        "unintuitively",
        "unitless",
        "UNITTESTS",
        "Unsort",
        "UPDATEME",
        "ushort",
        "ushortint",
        "Vadali",
        "valgrind",
        "Vallado",
        "videogame",
        "vpath",
        "wchar",
        "webassembly",
        "webp",
        "Wextra",
        "worky",
        "Wshadow",
        "Wuninitialized",
        "xaxis",
        "xlabel",
        "xlim",
        "xticklabels",
        "xticks",
        "XVCJ",
        "Ybdn",
        "ylabel",
        "ylim",
        "yscale",
        "yticks",
        "zlabel",
        "Zubrin"
    ],
    "cSpell.enableFiletypes": [
        "doxygen",
        "makefile",
        "markdown",
        "markdown_latex_combined",
        "swig",
        "tex",
        "typst"
    ],
    "editor.guides.highlightActiveIndentation": "always",
    "javascript.suggest.autoImports": false,
    "typescript.suggest.autoImports": false,
    "typescript.preferences.includePackageJsonAutoImports": "off",
    "python.analysis.autoImportCompletions": false,
    "security.workspace.trust.untrustedFiles": "open",
    "workbench.editor.untitled.hint": "hidden",
    "markdown.preview.fontSize": 15,
    "workbench.tips.enabled": false,
    "clang-format.fallbackStyle": "Google",
    "[cpp]": {
        "editor.defaultFormatter": "xaver.clang-format"
    },
    "shellcheck.exclude": [
        "SC2015"
    ],
    "cSpell.useGitignore": false,
    "git.confirmSync": false,
    "markdown.preview.markEditorSelection": false,
    "json.schemas": [
        {
            "fileMatch": [
                "*.json"
            ],
            "schema": {
                "allowTrailingCommas": true
            }
        }
    ],
    "editor.lineHeight": 1.2,
    "terminal.integrated.commandsToSkipShell": [
        "language-julia.interrupt"
    ],
    "julia.symbolCacheDownload": true,
    "julia.enableTelemetry": true,
    "editor.bracketPairColorization.independentColorPoolPerBracketType": true,
    "matlab.mlintpath": "/usr/local/MATLAB/R2022b/bin/glnxa64/mlint",
    "[python]": {
        "editor.formatOnType": false,
        "editor.defaultFormatter": "ms-python.autopep8"
    },
    "rust-analyzer.inlayHints.typeHints.enable": false,
    "rust-analyzer.inlayHints.parameterHints.enable": false,
    "editor.unicodeHighlight.allowedCharacters": {
        "σ": true,
        "α": true,
        "×": true
    },
    "editor.unicodeHighlight.includeComments": true,
    "workbench.editorAssociations": {
        "*.pdf": "latex-workshop-pdf-hook"
    },
    "cSpell.ignorePaths": [
        "package-lock.json",
        "node_modules",
        "vscode-extension",
        ".git/objects",
        ".vscode",
        ".vscode-insiders",
        "engine/input",
        "enigne/output"
    ],
    // "rust-analyzer.completion.snippets.custom": {
    //   "Arc::new": {
    //     "postfix": "arc",
    //     "body": "Arc::new(${receiver})",
    //     "requires": "std::sync::Arc",
    //     "description": "Put the expression into an `Arc`",
    //     "scope": "expr"
    //   },
    //   "Rc::new": {
    //     "postfix": "rc",
    //     "body": "Rc::new(${receiver})",
    //     "requires": "std::rc::Rc",
    //     "description": "Put the expression into an `Rc`",
    //     "scope": "expr"
    //   },
    //   "Box::pin": {
    //     "postfix": "pinbox",
    //     "body": "Box::pin(${receiver})",
    //     "requires": "std::boxed::Box",
    //     "description": "Put the expression into a pinned `Box`",
    //     "scope": "expr"
    //   },
    //   "Ok": {
    //     "postfix": "ok",
    //     "body": "Ok(${receiver})",
    //     "description": "Wrap the expression in a `Result::Ok`",
    //     "scope": "expr"
    //   },
    //   "Err": {
    //     "postfix": "err",
    //     "body": "Err(${receiver})",
    //     "description": "Wrap the expression in a `Result::Err`",
    //     "scope": "expr"
    //   },
    //   "Some": {
    //     "postfix": "some",
    //     "body": "Some(${receiver})",
    //     "description": "Wrap the expression in an `Option::Some`",
    //     "scope": "expr"
    //   }
    // },
    "rust-analyzer.inlayHints.closingBraceHints.enable": false,
    "editor.fontSize": 12.5,
    "rust-analyzer.completion.autoimport.enable": false,
    "editor.inlineSuggest.enabled": false,
    "editor.showFoldingControls": "always",
    "[javascript]": {
        "editor.defaultFormatter": "vscode.typescript-language-features"
    },
    "todohighlight.isEnable": true,
    "todohighlight.include": [
        "**/*.js",
        "**/*.jsx",
        "**/*.ts",
        "**/*.tsx",
        "**/*.html",
        "**/*.css",
        "**/*.scss",
        "**/*.php",
        "**/*.rb",
        "**/*.txt",
        "**/*.mdown",
        "**/*.md",
        "**/*.m",
        "**/*.typ",
        "**/*.json",
        "**/*.c",
        "**/*.cc",
        "**/*.cpp",
        "**/*.h",
        "**/*.hh",
        "**/*.hpp",
        "**/*.rs"
    ],
    "latex-workshop.message.error.show": false,
    "latex-workshop.message.warning.show": false,
    "latex-workshop.latex.autoBuild.run": "never",
    "latex-workshop.latex.external.build.command": "latexmk",
    "git.openRepositoryInParentFolders": "never",
    "typst-lsp.exportPdf": "never",
    "[yaml]": {
        "rewrap.autoWrap.enabled": false,
        "editor.insertSpaces": true,
        "editor.tabSize": 2,
        "editor.autoIndent": "advanced",
        "diffEditor.ignoreTrimWhitespace": false,
    },
    "[makefile]": {
        "editor.insertSpaces": false
    },
    "window.titleBarStyle": "custom",
    "terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe",
    "telemetry.telemetryLevel": "off",
    "MATLAB.telemetry": false,
    "julia.execution.saveOnEval": true,
    "vite.autoStart": false,
    "editor.snippetSuggestions": "none",
    "rust-analyzer.completion.callable.snippets": "add_parentheses",
    "typescript.updateImportsOnFileMove.enabled": "always",
    "[typescript]": {
        "editor.defaultFormatter": "vscode.typescript-language-features"
    },
    "settingsSync.ignoredExtensions": [
        "vite",
        "julia",
        "julialang.language-julia"
    ],
    "remote.SSH.remotePlatform": {
        "fsl.jsc.nasa.gov": "linux"
    },
    "git.defaultBranchName": "master",
    "julia.workspace.showModules": false,
    "editor.quickSuggestions": {
        "comments": "off",
        "strings": "off",
        "other": "off"
    },
    "editor.parameterHints.enabled": false,
    "rust-analyzer.inlayHints.chainingHints.enable": false,
    "autopep8.args": [
        "--indent-size=2",
        "--max-line-length=80",
        "--ignore=E121"
    ],
    "search.followSymlinks": false,
    "MATLAB.matlabConnectionTiming": "onDemand",
    "[typst]":{
        "editor.wordWrap": "on",
        "editor.semanticHighlighting.enabled": true,
        "editor.wrappingIndent": "indent"
    },
    "lldb.suppressUpdateNotifications": true,
    "editor.suggest.selectionMode": "never",
    "workbench.activityBar.visible": false,
    "workbench.colorTheme": "Gremlin",
    "cmake.configureOnOpen": true,
    "editor.lightbulb.enabled": false
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants