json summary in python

  • 2020-12-09 00:57:12
  • OfStack

JSON(JavaScript Object Notation object Spectrum) is a lightweight data exchange format. It is based on a subset of ECMAScript (the js specification developed by the European Computer Society) and uses a completely programming language-independent text format to store and represent data. The concise and clear hierarchy makes JSON an ideal data exchange language. Easy to read and write, but also easy to machine parsing and generation, and effectively improve the efficiency of network transmission.

Here is an introduction to json in python, starting with 1

JSON

JSON(Java Script Object Notation)

Using json you must import the json library :import json

dumps() json's formatting converts dictionaries to strings


>>> import json
>>> data = {'a':1,'b':2,'c':3}
>>> json.dumps(data)
'{"a": 1, "b": 2, "c": 3}'

indent is the specified indenting number


>>>json.dumps(data,indent=4) //4 Is the number covered 

separators() function is element delimiter, object key value delimiter (to make json files more compact)


>>>json.dumps(data,separators(',',':'))
{"a":1,"b":[1,2,3],"c":3}

ensure_ascii() Solves the confusion problem when there are Chinese characters in the dictionary (ehsure_ascii = False) (json defaults to ascii code).


>>>s = json.dumps(data,nsure_ascii=False)

dump() json writes to the file


>>> with open(r'C:\Users\test.json','w') as f:
...   json.dump(data,f)
...
>>>with open(r'C:\Users\test.json','r') as f:
...  f.read()
...
'{"a": 1, "b": 2, "c": 3}'

loads() converts the json file into a dictionary


>>> s = json.dumps(data)
>>> s
'{"a": 1, "b": 2, "c": 3}'
>>> json.loads(s)
{'a': 1, 'b': 2, 'c': 3}
>>>

load() reads json data from a file


>>> with open(r'C:\Users\gallo\Desktop\python\ Little game \practice\test.json','r') as f:
...   json.load(f)
...
{'a': 1, 'b': 2, 'c': 3}
>>>

conclusion


Related articles: