Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dump json into yaml

Tags:

I got a .json file (named it meta.json) like this:

{     "main": {         "title": "今日は雨が降って",         "description": "今日は雨が降って"     } } 

I would like to convert it to a .yaml file (named it meta.yaml) like :

title: "今日は雨が降って" description: "今日は雨が降って" 

What I have done was :

import simplejson as json import pyyaml  f = open('meta.json', 'r') jsonData = json.load(f) f.close()  ff = open('meta.yaml', 'w+') yamlData = {'title':'', 'description':''} yamlData['title'] = jsonData['main']['title'] yamlData['description'] = jsonData['main']['description'] yaml.dump(yamlData, ff) # So you can  see that what I need is the value of meta.json      

But sadly, what I got is following:

{description: "\u4ECA\u65E5\u306F\u96E8\u304C\u964D\u3063\u3066", title: "\u4ECA\u65E5\ \u306F\u96E8\u304C\u964D\u3063"} 

Why?

like image 888
holys Avatar asked Apr 11 '13 06:04

holys


People also ask

Can we convert JSON to YAML?

Users can also Convert JSON File to YAML by uploading the file. When you are done with JSON to YAML converting. You can download as a file or create a link and share. JSON to YAML Transformer works well on Windows, MAC, Linux, Chrome, Firefox, Edge, and Safari.

What is YAML dump?

Dumping YAML dump accepts the second optional argument, which must be an open text or binary file. In this case, yaml. dump will write the produced YAML document into the file. Otherwise, yaml. dump returns the produced document.

Is YAML better than JSON?

YAML is better suitable for configuration than JSON, whereas JSON is suitable for serialization format and transferring the data for API. JSON is good for human readability and suitable for serialization. It is explicit and can transmit the data over HTTP.

What is YAML Safe_load?

Loading a YAML Document Safely Using safe_load() safe_load(stream) Parses the given and returns a Python object constructed from the first document in the stream. safe_load recognizes only standard YAML tags and cannot construct an arbitrary Python object.


1 Answers

pyyaml.dump() has "allow_unicode" option, it's default is None, all non-ASCII characters in the output are escaped. If allow_unicode=True write raw unicode strings.

yaml.dump(data, ff, allow_unicode=True) 

bonus

json.dump(data, outfile, ensure_ascii=False) 
like image 139
shoma Avatar answered Oct 12 '22 12:10

shoma