使用sed修复没有引号的json文件

时间:2016-11-08 09:12:22

标签: json sed

如何使用sed或perl或任何shell脚本工具修复没有引号的json文件?那就是加上双引号(例如“词汇表”)。以下是json示例。非常感谢!

{
    glossary: {
        title: "example glossary",
            GlossDiv: {
                title: "S",
                GlossList: {
                    GlossEntry: {
                        ID: "SGML",
                        SortAs: "SGML",
                        GlossTerm: "Standard Generalized Markup Language",
                        Acronym: "SGML",
                        Abbrev: "ISO 8879:1986",
                        GlossDef: {
                            para: "A meta-markup language, used to create markup languages such as DocBook.",
                            GlossSeeAlso: ["GML", "XML"]
                        },
                    GlossSee: "markup"
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这个快速而肮脏的单行程适用于您的示例。但是,您的json格式必须与输入示例“相同”。属性名称也应遵循以下模式:[a-zA-Z_]+

sed -r 's/(\s*)([a-zA-Z_]+)/\1"\2"/' file

输出:

{
    "glossary": {
        "title": "example glossary",
            "GlossDiv": {
                "title": "S",
                "GlossList": {
                    "GlossEntry": {
                        "ID": "SGML",
                        "SortAs": "SGML",
                        "GlossTerm": "Standard Generalized Markup Language",
                        "Acronym": "SGML",
                        "Abbrev": "ISO 8879:1986",
                        "GlossDef": {
                            "para": "A meta-markup language, used to create markup languages such as DocBook.",
                            "GlossSeeAlso": ["GML", "XML"]
                        },
                    "GlossSee": "markup"
                }
            }
        }
    }
}