如何将json doc修剪为单行

时间:2017-10-24 09:03:54

标签: python json ansible

我正在使用json2yaml将yaml doc转换为json字符串。现在我想将json doc作为单行参数传递给// the Employee object function Employee( name, email, role ) { this.name = name; this.email = email; this.role = role; } Employee.prototype.helloEmployee = function() { console.log( "Oye" + this.role); } // the emp object inherits from Employee function emp( name, email ) { Employee.call(this, name, email, "admin"); } emp.prototype = Object.create( Employee.prototype ); var kumar = new emp( "Kumar", "info@helloitskumar.com" ); kumar.helloEmployee();,以便覆盖存储库设置。

例如:

YAML:

id

json doc :(这是由'json2yaml'网页生成的)

Object.assign(array.find(o => o.id === id) || {}, { selected: true });
//            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^                             find object
//                                                ^^^^^^^^^^^^^^^^^^   update value

我正在使用shell命令,如下所示: ansible_extravars

这显然也剥离了container: name: "summary" version: "1.0.0" some_level: "3" another_nested: schema: "summary" items_string: "really just a string of words"

中的空白区域

输出: { "container": { "name": "summary", "version": "1.0.0", "some_level": "3", "another_nested": { "schema": "summary", "items_string": "really just a string of words" } } }

如何将json doc转换为单行并在引用的字符串中保留空格?

2 个答案:

答案 0 :(得分:0)

我想出了以下python脚本:

#!/usr/bin/env python

import sys

filter_chars = [' ', '\t', '\n', '\r']


def is_filtered_char(c):
    return c in filter_chars


def is_filtered_eol_char(c):
    return c in ['\n', '\r']

inside_double_quoted_string = inside_single_quoted_string = False
some_chars = sys.stdin.read()
for c in some_chars:
    if c == '"':
        if not inside_double_quoted_string:
            inside_double_quoted_string = True
        else:
            inside_double_quoted_string = False
    if c == "'":
        if not inside_single_quoted_string:
            inside_single_quoted_string = True
        else:
            inside_single_quoted_string = False

    if not inside_double_quoted_string and not inside_single_quoted_string and not is_filtered_char(c):
        sys.stdout.write(c)
    elif (inside_double_quoted_string or inside_single_quoted_string) and not is_filtered_eol_char(c):
        sys.stdout.write(c)

```

Usgage:

% cat blah.txt | ./remove_ws.py {"container":{"name":"summary","version":"1.0.0","some_level":"3","another_nested":{"schema":"summary","items_string":"really just a string of words"}}}

答案 1 :(得分:0)

您只需要使用tr -d '[\r\n]'而不是所有空格来删除换行符。