Python Scripts for Converting Copied Interface Data and URL Queries to JSON
This article provides two Python scripts that transform raw interface‑copied data and URL query strings into properly formatted JSON, including dependency details, sample input, conversion code, and resulting output, offering a straightforward solution for developers handling unquoted JSON-like text.
Many users report that data copied from interfaces often lacks proper JSON quoting, making manual processing tedious even with semi‑automatic tools like Sublime Text. To simplify this task, two Python scripts are presented for reference.
Dependency : from urllib.parse import urlsplit, parse_qs 1. Converting interface‑copied data to JSON
The raw data (saved in json_to_json.txt) looks like:
AAA:aaa
BBB:{"BBB01":"bbb01"}
CCC:[ccc]The conversion script is:
# Interface‑copied data without quotes → JSON
def json_json():
f = open("json_to_json.txt", "r") # read
a = open("new_json_to_json.txt", "a+") # write
for line in f.readlines():
if "[" in line.strip() or "{" in line.strip():
print("'" + line.strip().replace(":", "':").replace(" ", "") + ",")
a.write("'" + line.strip().replace(":", "':").replace(" ", "") + "," + "
")
else:
print("'" + line.strip().replace(":", "':'").replace(" ", "") + "'" + ",")
a = open("/new_json.txt", "a+")
a.write("'" + line.strip().replace(":", "':'").replace(" ", "") + "'" + "," + "
")Running the script produces:
'AAA':'aaa',
'BBB':{"BBB01"':"bbb01"},
'CCC':[ccc],2. Converting a URL query string to JSON
The original URL (saved in query_to_json.txt) is:
https://www.baidu.com/s?tn=88093251_47_hao_pg&ie=utf-8&wd=Jenkins%20androidThe parsing script is:
def query_json():
f = open("query_to_json.txt", "r")
url = f.read()
query = urlsplit(url).query
params = dict(parse_qs(query))
ddd = {k: v[0] for k, v in params.items()}
print(ddd)Executing it yields the following dictionary:
{
'tn': '88093251_47_hao_pg',
'ie': 'utf-8',
'wd': 'Jenkins android'
}These scripts offer a quick way to turn unquoted, raw data and query strings into valid JSON structures for further processing.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
