Handling a Txt file content as a String Variable - python

I have a json file, and I need to read all of that json file content as String data. How can I read all the data and set a variable as a String for all of that content? Json file has blanks, new lines, special characters etc if it's neccesarry.
Thanks for your help!

import json
from ast import literal_eval
with open('<path_to_json_data>/json_data.txt') as f:
json_data = json.load(f) # dict object
print(json_data, type(json_data))
json_data_as_str = str(json_data) # dict-->str object
print(json_data_as_str, type(json_data_as_str))
data = literal_eval(json_data_as_str) # str-->dict object again
print(data, type(data))
Hope it helps

Simple as this example
import json
with open("path/to/json/filename.json", "r") as json_file:
data = json.load(json_file)
print(data)
dataStr = json.dumps(data)
print(dataStr)

use json.loads
import json
with open(file_name, "r") as fp:
as_string = str(json.loads(fp.read()))

Related

How can I edit my code to print out the content of my created json file?

My program takes a csv file as input and writes it as an output file in json format. On the final line, I use the print command to output the contents of the json format file to the screen. However, it does not print out the json file contents and I don't understand why.
Here is my code that I have so far:
import csv
import json
def jsonformat(infile,outfile):
contents = {}
csvfile = open(infile, 'r')
reader = csvfile.read()
for m in reader:
key = m['No']
contents[key] = m
jsonfile = open(outfile, 'w')
jsonfile.write(json.dumps(contents))
csvfile.close()
jsonfile.close()
return jsonfile
infile = 'orders.csv'
outfile = 'orders.json'
output = jsonformat(infile,outfile)
print(output)
Your function returns the jsonfile variable, which is a file.
Try adding this:
jsonfile.close()
with open(outfile, 'r') as file:
return file.read()
Your function returns a file handle to the file jsonfile that you then print. Instead, return the contents that you wrote to that file. Since you opened the file in w mode, any previous contents are removed before writing the new contents, so the contents of your file are going to be whatever you just wrote to it.
In your function, do:
def jsonformat(infile,outfile):
...
# Instead of this:
# jsonfile.write(json.dumps(contents))
# do this:
json_contents = json.dumps(contents, indent=4) # indent=4 to pretty-print
jsonfile.write(json_contents)
...
return json_contents
Aside from that, you aren't reading the CSV file the correct way. If your file has a header, you can use csv.DictReader to read each row as a dictionary. Then, you'll be able to use for m in reader: key = m['No']. Change reader = csvfile.read() to reader = csv.DictReader(csvfile)
As of now, reader is a string that contains all the contents of your file. for m in reader makes m each character in this string, and you cannot access the "No" key on a character.
a_file = open("sample.json", "r")
a_json = json.load(a_file)
pretty_json = json.dumps(a_json, indent=4)
a_file.close()
print(pretty_json)
Using this sample to print the contents of your json file. Have a good day.

Python save request cookies into json properly

Hi I would like to save my python requests cookies into a text file as json like so:
{"Proxy": "Cookies"}
At the moment im using:
with open('data.txt') as f:
proxy_data = json.load(f)
r = requests.get(URL,proxies=proxies, cookies=proxy_data['127:000'])
proxy_data['127:000'] = dict(session.cookies)
with open('data.txt', 'w') as json_file:
json.dump(proxy_data, json_file)
My data.txt file looks like this after writing it:
{"127:000": "{\"__cf_bm\": \"628f4c77a5139148cf28961a73f4edffed52f8c1-1622925414-1800-AaLguAyS9Hfl8TXCaQYUjjZ5i3sDck15kn/vcPJCWZBxi+nM9xU0zd/GfyKJu6/3R+GQEFdk/DGHEV4mANvpG1UMvcsXA9G9l/AFNEnIknTv\", \"cf_clearance\": \"84bffd070fbafcb91edcfa82f8cc3ba5a60a618d-1622925414-0-150\", \"cf_chl_seq_b116a013f9e2c44\": \"d3ac4406fc56d30\"}"}
However I run into a number of errors here. How can I do the properly?
UPDATE
ERRORS I GET
Python\Python37\lib\site-packages\requests\cookies.py", line 524, in
cookiejar_from_dict
cookiejar.set_cookie(create_cookie(name, cookie_dict[name])) TypeError: string indices must be integers
Currently, the value of proxy_data["127:000"] is a string which you're passing into the cookies parameter.
with open("data.txt") as f:
proxy_data = json.load(f)
print(type(proxy_data["127:000"]))
# >> <class 'str'>
Two options:
Parse the value of proxy_data["127:000"] to a dictionary using json.loads
r = requests.get(URL, proxies=proxies, cookies=json.loads(proxy_data['127:000']))
Make sure to save the nested dicts correctly.
proxy_data = {"127:000": {"cookie_test": "value_test"}}
with open("data.txt", "w") as f:
f.write(json.dumps(proxy_data))
with open("data.txt", "r") as f:
proxy_data = json.loads(f.read())
print(type(proxy_data["127:000"]))
# >> <class 'dict'>

how to read json file without using json libarary or without any other libarary in to dictionary or list?

I have a JSON file and i need to read it into dictionary or list without using and library.This is my file content.
{
"101":"Break and Enter Commercial",
"102":"Break and Enter Residential/Other",
"103":"Vehicle Collision or Pedestrian Struck (with Fatality)",
"104":"Vehicle Collision or Pedestrian Struck (with Injury)"
}
This is what i try
def read_codes(filename):
jsonData = {}
# empty list to append to it later
file = open(filename, "r")
for key in file:
print(key)
return jsonData
print(read_codes('codes.json'))
What about such way:
with open(file) as f:
your_dict = eval(f.read().replace('\n', ''))
You could open it as a text file. It would return you list, then filter the list as you require.
with open('file.json', 'r') as jsonFile:
json_obj = jsonFile.readlines()
json_obj = [(obj.rstrip()).lstrip()[:-1] for obj in json_obj[1:-1]]
print(json_obj)

loading json from text file

I am trying to run this code but it creates error.
import json
import requests
import pprint
data = []
with open('data.txt') as o1:
for line in o1:
data.append(json.loads(line))
print(data)
print(" \n")
print(data)
url = 'http://xyz.abcdfx.in/devicedata'
body_json=json.dumps(data)
headers = {'Content-Type':'application/json'}
d = requests.post(url, data = body_json, headers=headers)
pprint.pprint(d.json())
it shows
Value Error: No json object could be Decoded
I am new to programming and not able to figure out what is the problem.
It seems like you are trying to parse the json file line by line, but the json objects may (and usually are) span more than one line. You need to have the entire file in order to parse it:
with open('data.txt') as o1:
data = json.loads(o1.read()) # read ALL the file and parse. no loops
print(data)
i solved my problem using this:
data =[]
with open('data.txt') as f:
for line in f:
data = json.loads(line)
print(data)
url = 'http://xyz.abcdfx.cn/devicedata'
body_json=json.dumps(data)
headers = {'Content-Type':'application/json'}
d = requests.post(url, data = body_json, headers=headers)
pprint.pprint(d.json())

Python Search File Returning []

I'm trying to search a JSON file for the username but it is just returning [] rather than tom123.
JSON file contents:
[{"id":"001788fffe48cbdb","username":"tom123"}]
Code:
import json
import re
import requests
f = open("first.json", "r+")
print(f.read())
username = [index["username"] for index in f.read()]
print(username)
f.close()
maybe something like this you want to parse the json so you can use it like a dict
import json
import re
import requests
f = open("first.json", "r+")
data = json.loads(f.read())
username = [index["username"] for index in data]
print(username)
f.close()
f is a file object which is a iterator-like object, which means that when you iterate over it you've consumed it and you cannot use it again. And in this case you consume it first in following line:
print(f.read())
Also for loading a json file you should use json.load() function. Then you can preserve the content after reading then search though the preserved content:
with open("first.json") as f
content = json.load(f)
username = [index["username"] for index in content]
print(username)
Also as a functional-based approach you can use operator.itemgetter and map() in order to get an iterator contain all the usernames (which is more optimized in terms of memory use):
from operator import itemgetter
with open("first.json") as f
content = json.load(f)
usernames = map(itemgetter("username"), content)

Categories