简体   繁体   English

在 Python 中传递 JSON 的困难

[英]Difficulty in passing JSON in Python

I'm unable to parse JSON .我无法解析JSON My JSON snippet returned from requests.post response :-我从requests.post响应返回的JSON片段:-

{'result': {'parent': '', 'reason': '', 'made_sla': 'true', 'backout_plan': '', 'watch_list': '', 'upon_reject': 'cancel', 'sys_updated_on': '2018-08-22 11:16:09', 'type': 'Comprehensive', 'conflict_status': 'Not Run', 'approval_history': '', 'number': 'CHG0030006', 'test_plan': '', 'cab_delegate': '', 'sys_updated_by': 'admin', 'opened_by': {'link': 'https://dev65345.service-now.com/api/now/table/sys_user/6816f79cc0a8016401c5a33be04be441', 'value': '6816f79cc0a8016401c5a33be04be441'}, 'user_input': '', 'requested_by_date': '', 'sys_created_on': '2018-08-22 11:16:09', 'sys_domain': {'link': 'https://dev65345.service-now.com/api/now/table/sys_user_group/global', 'value': 'global'}, 'state': '-5', 'sys_created_by': 'admin', 'knowledge': 'false', 'order': '', 'phase': 'requested', 'closed_at': '', 'cmdb_ci': '', 'delivery_plan': '', 'impact': '3', 'active': 'true', 'review_comments': '', 'work_notes_list': '', 'business_service': '', 'priority': '4', 'sys_domain_path': '/', 'time_worked': '', 'cab_recommendation': '', 'expected_start': '', 'production_system': 'false', 'opened_at': '2018-08-22 11:16:09', 'review_date': '', 'business_duration': '', 'group_list': '', 'requested_by': {'link': 'https://dev6345.service-now.com/api/now/table/sys_user/user1', 'value': 'user1'}, 'work_end': '', 'change_plan': '', 'phase_state': 'open', 'approval_set': '', 'cab_date': '', 'work_notes': '', 'implementation_plan': '', 'end_date': '', 'short_description': '', 'close_code': '', 'correlation_display': '', 'delivery_task': '', 'work_start': '', 'assignment_group': {'link': 'https://dev65345.service-now.com/api/now/table/sys_user_group/testgroup', 'value': 'testgroup'}, 'additional_assignee_list': '', 'outside_maintenance_schedule': 'false', 'description': '', 'on_hold_reason': '', 'calendar_duration': '', 'std_change_producer_version': '', 'close_notes': '', 'sys_class_name': 'change_request', 'closed_by': '', 'follow_up': '', 'sys_id': '436eda82db4023008e357a61399619ee', 'contact_type': '', 'cab_required': 'false', 'urgency': '3', 'scope': '3', 'company': '', 'justification': '', 'reassignment_count': '0', 'review_status': '', 'activity_due': '', 'assigned_to': '', 'start_date': '', 'comments': '', 'approval': 'requested', 'sla_due': '', 'comments_and_work_notes': '', 'due_date': '', 'sys_mod_count': '0', 'on_hold': 'false', 'sys_tags': '', 'conflict_last_run': '', 'escalation': '0', 'upon_approval': 'proceed', 'correlation_id': '', 'location': '', 'risk': '3', 'category': 'Other', 'risk_impact_analysis': ''}}

I searched on the net.我在网上搜索过。 It is showing as as it is single quotes it's not parsing.它显示为单引号,它没有解析。

So I tried to convert the single quotes into double quotes.所以我尝试将单引号转换为双引号。

with open ('output.json','r') as handle:
  handle=open('output.json')
str="123"
str=handle.stringify() #also with .str()
str = str.replace("\'", "\"")
jsonobj=json.load(json.dumps(handle))

But it shows me No attribute stringify or str as it is an json object and these are string object function.但它显示我No attribute stringify or str因为它是一个json对象,这些是字符串对象函数。 So, can you please help me with what is the correct way of parsing the json object with single quotes in a file.那么,您能否帮助我了解在文件中使用单引号解析json对象的正确方法是什么。

The code:-编码:-

import requests
import json
from pprint import pprint

print("hello world")

url="********"

user="****"
password="*****"
headers={"Content-Type":"application/xml","Accept":"application/json"}

#response=requests.get(url,auth=(user,password),headers=headers)
response = requests.post(url, auth=(user, password), headers=headers ,data="******in xml****")

print(response.status_code)
print(response.json())

jsonobj=json.load(json.dumps(response.json()))
pprint(jsonobj)

What you receive from requests.post is not JSON, it's a dictionary.您从requests.post收到的不是 JSON,而是一本字典。

One that can be encoded in JSON, via json.dumps(result) .可以通过json.dumps(result)用 JSON编码的一种。

JSON is a text format to represent objects (the "ON" means "object notation"). JSON 是一种表示对象的文本格式(“ON”表示“对象符号”)。 You can convert a dictionary (or list or scalar) into a JSON-encoded string, or the other way around.您可以将字典(或列表或标量)转换为 JSON 编码的字符串,或者反过来。

What requests.post does is taking the JSON response and already parsing it (with json.loads ), so you don't have to think about JSON at all. requests.post所做的是获取 JSON 响应并已经对其进行解析(使用json.loads ),因此您根本不必考虑 JSON。

You haven't shown the code where you get the data from the post.您尚未显示从帖子中获取数据的代码。 However, you are almost certainly doing something like this:但是,您几乎肯定会做这样的事情:

response = requests.post('...')
data = response.json()

Here data is already parsed from JSON to a Python dict;这里的data已经从 JSON 解析为 Python dict; that is what the requests json method does.这就是 requests json方法所做的。 There is no need to parse it again.没有必要再次解析它。

If you need raw JSON rather than Python data, then don't call the json method.如果您需要原始 JSON 而不是 Python 数据,则不要调用json方法。 Get the data direct from the response:直接从响应中获取数据:

data = response.content

Now data will be a string containing JSON.现在data将是一个包含 JSON 的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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