Yes, s stands for string. The json.loads function does not take the file path, but the file contents as a string. Look at the documentation.
Simple example:
with open("file.json") as f:
data = json.load(f) # ok
data = json.loads(f) # not ok, f is not a string but a file
text = '{"a": 1, "b": 2}' # a string with json encoded data
data = json.loads(text)
Answer from Gijs on Stack OverflowCan someone explain what the difference is between using either load() or loads() is with the JSON library? And which, if either, is the preferred method.
I'm writing a simple script where I want the JSON data from a URL parsed out into a list. Both of these options seem to work:
import json import urllib2 url = "string to url" response = urllib2.urlopen(url) data = json.load(response)
or
import json import urllib2 url = "string to url" response = urllib2.urlopen(url) data = json.loads(response.read())
I know that there are other libraries available for parsing out JSON data, but for the time being I'm working only with the json and urllib2 libraries.
Any insight into which one should be used?
Thanks
load() loads JSON from a file or file-like object
loads() loads JSON from a given string or unicode object
It's in the documentation
The "s" is an abbreviation for "string". "dump__s__" is read as "dump string". "load__s__" = "load string". Otherwise these methods want a file-like object. This convention is scattered throughout python and even 3rd-party packages.
Yes, s stands for string. The json.loads function does not take the file path, but the file contents as a string. Look at the documentation.
Simple example:
with open("file.json") as f:
data = json.load(f) # ok
data = json.loads(f) # not ok, f is not a string but a file
text = '{"a": 1, "b": 2}' # a string with json encoded data
data = json.loads(text)
Just going to add a simple example to what everyone has explained,
json.load()
json.load can deserialize a file itself i.e. it accepts a file object, for example,
# open a json file for reading and print content using json.load
with open("/xyz/json_data.json", "r") as content:
print(json.load(content))
will output,
{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
If I use json.loads to open a file instead,
# you cannot use json.loads on file object
with open("json_data.json", "r") as content:
print(json.loads(content))
I would get this error:
TypeError: expected string or buffer
json.loads()
json.loads() deserialize string.
So in order to use json.loads I will have to pass the content of the file using read() function, for example,
using content.read() with json.loads() return content of the file,
with open("json_data.json", "r") as content:
print(json.loads(content.read()))
Output,
{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
That's because type of content.read() is string, i.e. <type 'str'>
If I use json.load() with content.read(), I will get error,
with open("json_data.json", "r") as content:
print(json.load(content.read()))
Gives,
AttributeError: 'str' object has no attribute 'read'
So, now you know json.load deserialze file and json.loads deserialize a string.
Another example,
sys.stdin return file object, so if i do print(json.load(sys.stdin)), I will get actual json data,
cat json_data.json | ./test.py
{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
If I want to use json.loads(), I would do print(json.loads(sys.stdin.read())) instead.
Videos
Hi, hope everyone is well.
Just nearing the basics end of PCC book, I'm at saving user's data now. What exactly is the reason, when storing simple data, to use json.dump() or load(), instead of just saving and then reading it from simple text file?
I just can't place it in my head why do I really need it and it always makes it more difficult for me to learn if that's the case.
Thank you all in advance.
hey can anyone help me out here, my school gave me a json file, and I need to be able to read and write to and from that file in python, but I can't get it to work, and tutorials aren't really working out for me aswell. :(
https://github.com/DaanYouKnow/help
here is the file.
The json method of requests.models.Response objects ends up calling the json.loads method, but it may do something more.
You can see in the requests.models.Response.json source code that it sometimes tries to guess the encoding prior to calling complexjson.loads (which is in fact json.loads):
if not self.encoding and self.content and len(self.content) > 3:
# No encoding set. JSON RFC 4627 section 3 states we should expect
# UTF-8, -16 or -32. Detect which one to use; If the detection or
# decoding fails, fall back to `self.text` (using chardet to make
# a best guess).
encoding = guess_json_utf(self.content)
So, it seems that it is in general probably better to use r.json() than json.loads(r.text).
.json is a method of requests.models.Response class. It returns json body data from the request's response.
import requests
r = requests.get('https://reqres.in/api/users?page=2')
print(type(r)) # <class 'requests.models.Response'>
r.json()
loads is a function from json package to parse string data
import json
print(type(r.text)) # <class 'str'>
json.loads(r.text)
json.loads can be used with any string data, not only in requests context
json.loads('{"key": "value"}')
I'm trying to read a JSON message from an MQTT broker, and while testing, I'm sending all kinds of strings. I've noticed some weird behavior and was hoping someone could explain it to me.
When I enter a string with JSON format, it loads into a dictionary as expected: https://imgur.com/Li6oDMk
However, if I input another string, it triggers an error. I'm able to catch the error and handle it differently: https://imgur.com/GERjNGu
But here's where it gets interesting – if the string consists entirely of numbers (either integers or floats), the JSON.loads directly parses it to an int or float: https://imgur.com/K2LEZ9y
So, is there something wrong with my version, or is this the correct behavior?