How to handle the json convert object in python - python

I have a JSON file which I converted in the python object using json.load() function.I want the output to be dict or list but its a string.
PS: The data I could not share because its a production data.
Thanks in advance:)

you mean you have file is myJsonfile.json right ?
and you want to load them into python?
you can using like this
import json
file = open('myjsonfile.json','r')
jsonfile = json.load(file)
to check data it's was python now call
jsonfile

to change from a string to dict/list use json.loads()
So what every your stored string is, in the example below I called is jsonStr:
jsonStr = '''{"file_type": "json" , "data_type": "str"}'''
jsonObj = json.loads(jsonStr)
Output:
print (jsonObj)
{'file_type': 'json', 'data_type': 'str'}
print (type(jsonObj))
<class 'dict'>

Related

Opening a json file from computer as a dictionary

I wrote the following function that I want to apply to a json file:
import json
def myfunction(dictionary):
#doing things
return new_dictionary
data = """{
#a json file as a dictionary
}"""
info = json.loads(data)
refined = key_replacer(info)
new_data = json.dumps(refined)
print(new_data)
It works fine, but how do I do it when I want to import a file from my computer? json.loads take a string as input and returns a dictionary as output and json.dumps take a dictionary as input and returns a string as output. I tried with:
with open('C:\\Users\\SONY\\Desktop\\test.json', 'r', encoding="utf8") as data:
info = json.loads(data)
But TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper.
You are passing a file object instead of string. To fix that, you need to read the file first json.loads(data.read())
Howerver, you can directly load json from files using json.load(open('myFile','r')) or in your case, json.load(data)
loads and dumps work on strings. If you want to work on files you should use load and dump instead.
Here is an example:
from json import dump, load
with open('myfile.json','r') as my_file:
content = load(my_file)
#do stuff on content
with open('myooutput.json','w') as my_output:
dump(content, my_output)

TypeError: ... is not JSON serializable error when adding new values to an object by Python

I have such a json object:
{
"people":[
{"firstName":"Hasan Sait", "lastName":"Arslan", "email":"hasan.sait.arslan#gmail.com"}]
}
I want to add new value to this json object by python as the following:
import json
with open('data.json', 'r+') as json_file:
json_data = json.load(json_file)
people = json_data['people']
people.append({"firstName":"Mehmet"})
json_file.seek(0, 0)
json.dump(json_file, json_data)
json_file.truncate()
I get the following error: TypeError: <open file 'data.json', mode 'r+' at 0x7f3f85a4b5d0> is not JSON serializable
In stackoverflow, there are similar questions to mine asked before, but I couldn't find any beneficial solution from them.
Could you tell me where I am wrong?
json.dumps doesn't write to streams, it simply takes the object and returns the JSON-serialized string. You can then save that to the file.
import json
with open('data.json', 'r+') as json_file:
json_data = json.load(json_file)
people = json_data['people']
people.append({"firstName":"Mehmet"})
json_file.seek(0, 0)
jsonString = json.dumps(json_data)
json_file.write(jsonString)
json_file.truncate()
You just got the order of json_file and json_data wrong, so it tells you that you can't use the filepointer as json. The object is first and the file pointer second when using json.dump.

Encoding a JSON file

I get this string from the web
'Probabilità'
and I save it in a variable called temp. Than I stored it in a dictionary
dict["key"]=temp
Then I need to write all the dictionary in a JSON file and I use this function
json_data = json.dumps(dict)
But when I look at the JSON file written by my code I see this
'Probabilit\u00e0'
How can I solve this encoding problem?
Specify the ensure_ascii argument in the json.dumps call:
mydict = {}
temp = "Probabilità"
mydict["key"] = temp
json_data = json.dumps(mydict, encoding="utf-8", ensure_ascii=False)

Read json file from python

I am trying to read a json file from python script using the json module. After some googling I found the following code:
with open(json_folder+json) as json_file:
json_data = json.loads(json_file)
print(json_data)
Where json_folder+json are the path and the name of the json file. I am getting the following error:
str object has no attribute loads.
The code is using json as a variable name. It will shadow the module reference you imported. Use different name for the variable.
Beside that, the code is passing file object, while json.loads accept a string.
Pass a file content:
json_data = json.loads(json_file.read())
or use json.load which accepts file-like object.
json_data = json.load(json_file)
import json
f = open( "fileToOpen.json" , "rb" )
jsonObject = json.load(f)
f.close()
it should seems you are doing in rather complicated way.
Try like this :-
json_data=open(json_file)
data = json.load(json_data)
json_data.close()
Considering the path to your json file is set to the variable json_file:
import json
with open(json_file, "rb") as f:
json_data = json.load(f)
print json_data
I Make This....
import urllib2
link_json = "\\link-were\\"
link_open = urllib2.urlopen(link_json) ## Open and Return page.
link_read = link_open.read() ## Read contains of page.
json = eval(link_read)[0] ## Transform the string of read in link_read and return the primary dictionary ex: [{dict} <- return this] <- remove this
print(json['helloKey'])
Hello World

How to parse values from a JSON file in Python

I'm trying to get the values from the json file and the error that I'm getting is TypeError: expected string or buffer. I'm parsing the file correctly and moreover I guess my json file format is also correct. Where I'm going wrong?
Both the files are in the same directory.
Main_file.py
import json
json_data = open('meters_parameters.json')
data = json.loads(json_data) // TypeError: expected string or buffer
print data
json_data.close()
meters_parameters.json
{
"cilantro" : [{
"cem_093":[{
"kwh":{"function":"3","address":"286","length":"2"},
"serial_number":{"function":"3","address":"298","length":"2"},
"slave_id":{"function":"3","address":"15","length":"2"}
}]
}],
"elmeasure" : [{
"lg1119_d":[{
"kwh":{"function":"3","address":"286","length":"2"},
"serial_number":{"function":"3","address":"298","length":"2"},
"slave_id":{"function":"3","address":"15","length":"2"}
}]
}]
}
loads expects a string not a file handle. You need json.load:
import json
with open('meters_parameters.json') as f:
data = json.load(f)
print data
You're trying to load the file object, when you want to load everything in the file. Do:
data = json.loads(json_data.read())
.read() gets everything from the file and returns it as a string.
A with statement is much more pythonic here as well:
with open('meters_parameters.json') as myfile:
data = json.loads(myfile.read())

Categories

Resources