Hướng dẫn python json dump one per line - python json dump một trên mỗi dòng
For fun I adapted my answer to another somewhat related question to make it do what you want. Note that currently it only changes the formatting of a 7 if it's in a list.
Sample usage:
Output: json.dump(s) & json.load(s)bogotobogo.com site search: json.load(s) & json.dump(s) There are two ways of reading in (load/loads) the following json file, in.json: {"alpha": 1, "beta": 2}
Both will print out: {'alpha': 1, 'beta': 2} Note that while the json.loads() requires string, load(s,...), the json.load() requires file descriptor, load(fp...). Similarly, we can write a (dump/dumps) json file:
Note that the json.dump() requires file descriptor as well as an obj, dump(obj, fp...). In the following example, we'll convert Python dictionary to JSON and write it to a text file. Then, we'll read in back from the file and play with it. Initially we'll construct Python dictionary like this: # Four Fundamental Forces with JSON d = {} d ["gravity"] = { "mediator":"gravitons", "relative strength" : "1", "range" : "infinity" } d ["weak"] = { "mediator":"W/Z bosons", "relative strength" : "10^25", "range" : "10^-18" } d ["electromagnetic"] = { "mediator":"photons", "relative strength" : "10^36", "range" : "infinity" } d ["strong"] = { "mediator":"gluons", "relative strength" : "10^38", "range" : "10^-15" } print(d) The output looks like this: 0Now, we want to convert the dictionary to a string using json.dumps: 1Output: 2Note that the "json.dumps()" returns a string as indicated by the "s" at the end of "dumps". This process is called encoding. Let's write it to a file: 3Now that the file is written. Let's reads it back and decoding the JSON-encoded string back into a Python dictionary data structure: 4Let's play with the dictionary a little bit. What's the relative strength of electromagnetic compared to gravity? 5Who's the mediator for "strong" force? 6Ok, here is the full code: 7If we prefer working with files instead of strings, we may want to use json.dump() / json.load() to encode / decode JSON data using the data from the previous example: 8 Here is another example (json.dump()/json.load()) using simpler data: 9 Usage for string version: json.loads()/json.dumps(): 0 The following example sends a syslog to logstash fargate containers behind AWS NLB: 1note that for the HOST, we can also use FQDN instead of the NLB's domain name. Also, as usual, instead of the long line of code, we may want to use a simple linux command, 8: 2If the NLB listener protocol is TLS, we can use 9 echo to the TLS NLB: 3 Another example: AWS API response. When we make an AWS API call, the response can be an invalid json due to datetime: 4We need to serialize it (ow to overcome “datetime.datetime not JSON serializable”?). Here is a boto3 code for an API call to EC2 describe: 5The r.json with jq looks like this: 6 Python tutorialPython Home |