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 :
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 .