你可以如何在Python中更改JSON格式。

huangapple go评论123阅读模式
英文:

How can i change the JSON format in Python

问题

我的JSON文件看起来像这样:

  1. {
  2. "GetEventHeadlines_Response_1":{
  3. "EventHeadlines":{
  4. "Headline":[
  5. {
  6. "CountryCode":"US",
  7. "EventType":"EarningsCallsAndPresentations",
  8. "Duration":{
  9. "EndDateTime":"2019-12-30T12:00:00",
  10. "EndQualifier":"None",
  11. "IsEstimate":false,
  12. "StartDateTime":"2019-12-30T12:00:00",
  13. "StartQualifier":"DateTime"
  14. },
  15. "EventId":12969284......
  16. }
  17. ]
  18. }
  19. }
  20. }

所以简而言之,我想要去掉开头和结尾的"以及\符号。

英文:

My JSON files looks like this

  1. "{\"GetEventHeadlines_Response_1\":{\"EventHeadlines\":
  2. {\"Headline\":[{\"CountryCode\":\"US\",\"EventType\":\"EarningsCallsAndPresentations\",
  3. \"Duration\":
  4. {\"EndDateTime\":\"2019-12-30T12:00:00\",\"EndQualifier\":\"None\", \"IsEstimate\":false,\"StartDateTime\":\
  5. "2019-12-30T12:00:00\",\"StartQualifier\":
  6. \"DateTime\"},\"EventId\":12969284......

I want to change this to

  1. {
  2. "GetEventHeadlines_Response_1":{
  3. "EventHeadlines":{
  4. "Headline":[
  5. {
  6. "CountryCode":"US",
  7. "Duration":{
  8. "EndDateTime":"2019-12-30T12:00:00",
  9. "EndQualifier":"None",
  10. "IsEstimate":false,
  11. "StartDateTime":"2019-12-30T12:00:00",
  12. "StartQualifier":"DateTime"
  13. },
  14. "EventId":12969284,.....

So in short i want to get rid of the ""(only at the beginning and end ) and the \ sign.

答案1

得分: 2

import json

data = '''{
"GetEventHeadlines_Response_1": {
"EventHeadlines": {
"Headline": [
{
"CountryCode": "US",
"EventType": "EarningsCallsAndPresentations",
"Duration": {
"EndDateTime": "2019-12-30T12:00:00",
"EndQualifier": "None",
"IsEstimate": false,
"StartDateTime": "2019-12-30T12:00:00",
"StartQualifier": "DateTime"
}
}
]
}
}
}'''

data = json.loads(json.dumps(data))
print(data)

英文:
  1. import json
  2. data = '''
  3. {\"GetEventHeadlines_Response_1\":{\"EventHeadlines\":
  4. {\"Headline\":[{\"CountryCode\":\"US\",\"EventType\":\"EarningsCallsAndPresentations\",
  5. \"Duration\":
  6. {\"EndDateTime\":\"2019-12-30T12:00:00\",\"EndQualifier\":\"None\", \"IsEstimate\":false,\"StartDateTime\":\
  7. "2019-12-30T12:00:00\",\"StartQualifier\":
  8. \"DateTime\"}
  9. '''
  10. data = json.loads(json.dumps(data))
  11. print(data)

答案2

得分: 0

import json

myUnfomattedJSON = "..."
jsonObj = json.loads(myUnformattedJSON)

formattedJSON = json.dumps(jsonObj, indent=2)

print(formattedJSON)

英文:
  1. import json
  2. myUnfomattedJSON = "..."
  3. jsonObj = json.loads(myUnformattedJSON)
  4. formattedJSON = json.dumps(jsonObj, indent=2)
  5. print(formattedJSON)

huangapple
  • 本文由 发表于 2020年1月6日 23:32:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/59614806.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定