Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.0k views
in Technique[技术] by (71.8m points)

python - json.dumps() produces stringed each line instead of regular json looking output

I use json.dumps un the loop to create an array of json payloads. now, if I use json.dumps on a single dict I get json string, if I put within a loop with array_name.append(payload_json), I get an array of things that look like this:

last line of the method is: return json.dumps(prr_payload, indent=2)

'{
'
  '  "key1": 1,
'
  '  "key2": "no-cache",
'
  '  "key3": true,
'
  '  "key4": "USD",
'
  '  "key5": "USD",
'
  '  "key6": "2021-03-23",
'
  '}',

basically stringed every line in that output.

here is complete code:

import random
import moment
import json
import pprint

pp = pprint.PrettyPrinter(indent=2, sort_dicts=True)

data = ["90d7b80e-209f-5d09-8af0-c38b0666575b", "e9503e77-ebd3-5b91-bbaf-00662b3e3bed", "bbdb6c49-15a1-511a-8899-e9757cf78a0c", "7e09edf7-499d-5152-ac0e-086fd12af1c1", "214a4985-0c82-550e-baf9-5be9cbfcaef7", "3232f693-bea1-53b2-9b4d-b72901a1738c"]

prr_payload =   { 
     "key1": 1, 
     "key2": "no-cache", 
     "key3": True, 
     "key4": "USD", 
     "key5": "USD" 
}

def generate_payload():
  # prr_payload = example_payload.copy()
  prr_payload['key2'] = moment.now().add(month=2).add(days=2).format('YYYY-MM-DD')
  prr_payload['key5'] = random.choice(data)
  prr_payload['key4'] = [random.randint(1,5), random.randint(1,10)]
  return json.dumps(prr_payload, indent=2)

# ppr_request = json.dumps(generate_payload(), indent=2)


print(generate_payload(), type(generate_payload()))

results = []
for payload in data:
  payload = generate_payload()
  print(type(payload))
  results.append(payload)

print(len(results))
pp.pprint(results)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...