简体   繁体   中英

Python: Change multi-line json String to single line

I have to pass the below string to a python command

'[{
  "action": "DELETE",
  "is_enabled": true,
  "name": "qe_ta_rule_kYKco6_ObjectLifecyclePolicy",
  "object_name_filter": null,
  "time_amount": 1,
  "time_unit": "DAYS"
}]'

Is there a way to replace all the newline characters so that i becomes a 1 line String

This is not a valid python string:

'[{
  "action": "DELETE",
  "is_enabled": true,
  "name": "qe_ta_rule_kYKco6_ObjectLifecyclePolicy",
  "object_name_filter": null,
  "time_amount": 1,
  "time_unit": "DAYS"
}]'

Multi-line strings should be like:

'[{ \
  "action": "DELETE", \
  "is_enabled": true, \
  "name": "qe_ta_rule_kYKco6_ObjectLifecyclePolicy", \
  "object_name_filter": null, \
  "time_amount": 1, \
  "time_unit": "DAYS" \
}]'

If this is coming from the web, it probably is coming like: '[{ \n "action": "DELETE", \n...'

Either way, you would replace the new lines like your_str.replace('\n', '')

You can use jq to achieve this:

Source JSON:

[
  {"empid": "1", "empname": "E1", "empsal": "100"},
  {"empid": "2", "empname": "E2", "empsal": "200"},
  {"empid": "3", "empname": "E3", "empsal": "300"}
]

Transformation:

cat source.json | jq -c '.[]' > target.json

Target JSON:

{"empid":"1","empname":"E1","empsal":"100"}
{"empid":"2","empname":"E2","empsal":"200"}
{"empid":"3","empname":"E3","empsal":"300"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM