How to remove text !!omap from yaml file?
In YAML mappings are defined to be not ordered, although of course the keys have a definite order in the YAML document.
Therefore, if you dump an explicitly ordered mapping, like Python's OrderedDict
the guaranteed ordering is by dumping
a sequence (always ordered) of single mappings, tagged with !!omap
. If you would read that output back, you will again
get an OrderedDict
when using ruamel.yaml
, so as you already noted there is nothing wrong (but some tools processing the output down the chain might not handle this properly).
Dictionaries in newer Python 3 implementations are ordered, and will be dumped without such tag and without the sequence needed
to guarantee the order. The same effect for Python 2.7+ can be achieved by using a CommentedMap
, which acts as an OrderedDict (without dumping a tag):
import sys
import ruamel.yaml
from ruamel.yaml.comments import CommentedMap as OrderedDict
file_path = 'input.yaml'
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_path))
yaml = ruamel.yaml.YAML()
yaml.indent(sequence=ind, offset=bsi) # set the original sequence indent and offset of the dash
allowed_attributes = ['Name', 'Children']
allowed_children = ['Rick', 'Stacy']
root_node_name = 'Person'
config[root_node_name] = OrderedDict((attribute_name, config[root_node_name][attribute_name]) for attribute_name in allowed_attributes)
config[root_node_name]['Children'] = [child_name for child_name in allowed_children]
yaml.dump(config, sys.stdout)
which gives:
Person:
Name: John
Children:
- Rick
- Stacy
Please note that the officially recommended extension for files containing YAML documents is .yaml
since 2007.
To add to the confusion, there is an even older, but not so often encountered YML format, which is an XML derivative.
So please consider updating your extensions and code.
How to delete an inherit property from yaml config?
No there isn't a way to mark a key
for deletion in a YAML file. You can only overwrite existing values.
And the latter is what you do, you associate the empty scalar as value to the key image
as if you would have written:
image: null # delete
There are two things you can do: post-process or make a base mapping in your YAML file.
If you want to post-process, you associate a special unique value to image
, or a specially tagged object, and after loading recursively walk over the tree to remove key-value pairs with this special value. Whether you can already do this during parsing, using hooks or overwriting some of its methods, depends on the parser.
Using a base mapping requires less work, but is more intrusive to the YAML file:
localbase: &lb
# *tons of config*
local: &local
image: xxx
ci:
<<: *lb
build: .
If you do the former you should note that if you use a parsers that preserve the "merge-hierarchy" on round-tripping (like my ruamel.yaml
parser can do) it is not enough to delete the key-value pair, in that case the original from local
would come back. Other parsers that simply resolve this at load time don't have this issue.
Remove property from yaml file
If you want to omit type
from your whole YAML, you can Marshal your data into an object where type
is not more exists
type OBJ struct {
Id string `yaml:"ID"`
Mod []*Mod `yaml:"mod,omitempty"`
}
type Mod struct {
Name string
//Type string `yaml:"type"`
Parameters Parameters `yaml:"parameters,omitempty"`
Build Parameters `yaml:"build,omitempty"`
}
type
will be removed, if you Marshal your data into this object.
Another solution if you do not want to use multiple object.
Use omitempty
in Type. So when value of Type is ""
, it will be ignored
type Mod struct {
Name string
Type string `yaml:"type,omitempty"`
Parameters Parameters `yaml:"parameters,omitempty"`
Build Parameters `yaml:"build,omitempty"`
}
And do this
for i, _ := range obj.Mod {
obj.Mod[i].Type = ""
}
Remove matching lines from yaml file
Use this (I've removed the -i
, and you can add it back when you're happy with the result):
sed '/^depends:/{N;N;d}' test.yml
Details:
/^depends:/
matches the first of the three lines{…}
goups the commands to be executed when the above pattern matched;
separates successive commandsN
appends the following line to the current pattern space (the line you were editing when the match occurred); this happens twice, resulting in the pattern space holding the line matching the pattern, plus the two following linesd
deletes the pattern space
Best way to remove element from Ruby hash array in yaml
require 'yaml'
ip = '1.2.3.4'
port = 3333
hash = YAML.load_file('ips.yml')
puts "hash (before): #{hash.inspect}"
hash[ip].delete(port) # here you are deleting the port (3333) from the ip (1.2.3.4)
puts "hash (after): #{hash.inspect}"
File.open('ips.yml', 'w') { |f| YAML.dump(hash, f) }
# hash (before): {"69.39.239.151"=>[7777, 8677, 8777], "69.39.239.75"=>[9677, 9377], "209.15.212.147"=>[8477, 7777], "104.156.244.109"=>[9999], "1.2.3.4"=>[3333, 4444]}
# hash (after): {"69.39.239.151"=>[7777, 8677, 8777], "69.39.239.75"=>[9677, 9377], "209.15.212.147"=>[8477, 7777], "104.156.244.109"=>[9999], "1.2.3.4"=>[4444]}
Related Topics
Failing Installing Pg Gem, "Mkmf.Rb Can't Find Header Files for Ruby" (MAC Osx 10.6.5)
Does Ruby Call Initialize Method Automatically
Net::Ssh Sudo Command Hangs After Entering Password
Override Ruby Constant in Subclass So Inherited Methods Use New Constant Instead of the Old
How to Declare a String with Both Single and Double Quotes in Yaml
How to Drop Columns Using Rails Migration
How to Round a Time Down to the Nearest 15 Minutes in Ruby
To Change Directory Inside a Ruby Script
Why Doesn't "Rails S" Work from the App Directory
Redirect User After Log in Only If It's on Root_Path
Sort a Collection of Objects by Number (Highest First) Then by Letter (Alphabetical)
Check If an Array Is Subset of Another Array in Ruby
In Ruby Why Does Nil.Id Return 4
Notification of Object Destruction in Ruby
Extract All Email Addresses from Some .Txt Documents Using Ruby