[vagrant@localhost python]$ pip3 install pyyaml
Collecting pyyaml
Downloading https://files.pythonhosted.org/packages/9e/a3/1d13970c3f36777c583f136c136f804d70f500168edc1edea6daa7200769/PyYAML-3.13.tar.gz (270kB)
100% |████████████████████████████████| 276kB 507kB/s
Installing collected packages: pyyaml
Running setup.py install for pyyaml … done
Successfully installed pyyaml-3.13
import yaml yaml_str = """ Date: 2018-08-10 PriceList: - item_id: 1000 name: Banana color: yellow price: 800 - item_id: 1001 name: Orange color: orange price: 1400 - item_id: 1002 name: Apple color: red price: 2400 """ data = yaml.load(yaml_str) for item in data['PriceList']: print(item["name"], item["price"])
yaml.scanner.ScannerError: while scanning for the next token
found character ‘\t’ that cannot start any token
in “
–
^
何故だ?
import yaml customer = [ { "name": "Yamada", "age": "35", "gender": "man"}, { "name": "Sato", "age": "58", "gender": "woman"}, { "name": "Kato", "age": "42", "gender": "man"}, { "name": "Nishi", "age": "22", "gender": "man"} ] yaml_str = yaml.dump(customer) print(yaml_str) print("--- --- ---") data = yaml.load(yaml_str) for p in data: print(p["name"])
書き出しは出来ますね。
[vagrant@localhost python]$ python3 app.py
– {age: ’35’, gender: man, name: Yamada}
– {age: ’58’, gender: woman, name: Sato}
– {age: ’42’, gender: man, name: Kato}
– {age: ’22’, gender: man, name: Nishi}
— — —
Yamada
Sato
Kato
Nishi
import yaml yaml_str = """ color_def: - &color1 "#FF0000" - &color2 "#00FF00" - &color3 "#0000FF" color: title: *color1 body: *color2 link: *color3 """ data = yaml.load(yaml_str) print("title=", data["color"]["title"]) print("body=", data["color"]["body"]) print("link=", data["color"]["link"])
yaml.scanner.ScannerError: while scanning for the next token
found character ‘\t’ that cannot start any token
in “
– &color1 “#FF0000”
なんだこれ?