程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python on reading JSON files and converting dictionaries to JSON strings

編輯:Python

Python About JSON File reading and dictionary with JSON String conversion problem


In recent projects, when simulating a request, you need to use hmac sh256 Algorithm generated signature , It went well at first . But once here , No matter what, the calculated signature is wrong . puzzled , Finally, it is found that the calculation algorithm requires that the body of the request sent is free of spaces and newlines json character string .

I started with the str Direct to string , But found ,str The translated dictionary has the following problems :

  • The quotation marks of the converted string are single quotation marks
  • Converted json The string contains spaces
  • None Value needs to be replaced with json Format null

It is also a matter of finding and replacing , Three replace It can be solved .
But the problem is , If the dictionary value If the value contains the above , Finding a replacement can be a big problem . I have encountered the problem that the value contains spaces , Let me toss for a long time . Last , Found the use of json The library will dict Turn to no newline and no space json The string method is solved , Here is a record .

Code :

import json
# Read json file -> dict
config = json.load(open("application.json", encoding="utf-8"))
print(f"{
config}\n")
# dict -> json character string 
result = json.dumps(config)
print(f"{
result}\n")
# dict -> json character string Solve coding problems 
result = json.dumps(config, ensure_ascii=False)
print(f"{
result}\n")
# dict -> json character string indent Parameter control formatting json
result = json.dumps(config, ensure_ascii=False, indent=2)
print(f"{
result}\n")
# dict -> json character string No line breaks and spaces 
result = json.dumps(config, ensure_ascii=False, separators=(",", ":"))
print(f"{
result}\n")
# dict -> json character string Sort by Dictionary a-z
result = json.dumps(config, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
print(f"{
result}\n")

result :

{
'name': ' Zhang San ', 'age': 10}
{
"name": "\u5f20\u4e09", "age": 10}
{
"name": " Zhang San ", "age": 10}
{

"name": " Zhang San ",
"age": 10
}
{
"name":" Zhang San ","age":10}
{
"age":10,"name":" Zhang San "}

The above is the notes of this time , May the little friends not get lost .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved