json.load loads from a file-like object. You either want to use json.loads:
json.loads(data)
Or just use json.load on the request, which is a file-like object:
json.load(request)
Also, if you use the requests library, you can just do:
import requests
json = requests.get(url).json()
Answer from Blender on Stack Overflowconvert a json string to python object - Stack Overflow
converting JSON to string in Python - Stack Overflow
Convert from string to json python.
How to convert following string to JSON in python - Stack Overflow
Are there online platforms for string to JSON file Python conversions?
How do you differentiate between creating a JSON string and saving it as a file in Python?
How can one revert a JSON string back to its Python form?
I've tried using
simplejson.load()andjson.load()but it gave me an error saying'str' object has no attribute 'read'
To load from a string, use json.loads() (note the 's').
More efficiently, skip the step of reading the response into a string, and just pass the response to json.load().
if you don't know if the data will be a file or a string.... use
import StringIO as io
youMagicData={
results:[...],
"max_id":1346534,
"since_id":0,
"refresh_url":"?since_id=26202877001&q=twitter",
.
.
.
}
magicJsonData=json.loads(io.StringIO(str(youMagicData)))#this is where you need to fix
print magicJsonData
#viewing fron the center out...
#youMagicData{}>str()>fileObject>json.loads
#json.loads(io.StringIO(str(youMagicData))) works really fast in my program and it would work here so stop wasting both our reputation here and stop down voting because you have to read this twice
from https://docs.python.org/3/library/io.html#text-i-o
json.loads from the python built-in libraries, json.loads requires a file object and does not check what it's passed so it still calls the read function on what you passed because the file object only gives up data when you call read(). So because the built-in string class does not have the read function we need a wrapper. So the StringIO.StringIO function in short, subclasses the string class and the file class and meshing the inner workings hears my low detail rebuild https://gist.github.com/fenderrex/843d25ff5b0970d7e90e6c1d7e4a06b1 so at the end of all that its like writing a ram file and jsoning it out in one line....
json.dumps() is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.
For instance, if one of the values is None, the str() would produce an invalid JSON which cannot be loaded:
>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
But the dumps() would convert None into null making a valid JSON string that can be loaded:
>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}
There are other differences. For instance, {'time': datetime.now()} cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).
Hello,
UPDATE:
The problem is that I need to change the convert the data from string type to JSON.
How I got to the respective string ?
I am writing out the data from a dict. (no, I cannot convert from dict to JSON due to the architecture of the code behind)
The dictionary has the following values in it:
('sid', 'something funny'), ('subtitle', 'Nothing yet'), ('date', 'Today'), ('weather': 'Hot')
Afterwards I do the following: (The data is required as a string)
for key in dicts:
data = data + key + ' : ' + result[key] + '\n'
Then I have to change from this
title: something funny
subtitle: Nothing yet
date: Today
weather: Hot
to this
{
'title': 'something funny',
'subtitle': 'Nothing yet',
'date': 'Today',
'weather': 'Hot',
}
So far I've tried some variation of the following (but with no luck):
json.dumps(data, separators=('\n', ': '), sort_keys=True)
Does anyone have an idea on how should I approach this?
Thanks in advance!
The json library in python has a function loads which enables you to convert a string (in JSON format) into a JSON. Following code for your reference:
import json
str1 = '{"a":"1", "b":"2"}'
data = json.loads(str1)
print(data)
Note: You have to use ' for enclosing the string, whereas " for the objects and its values.
The string in OP's question is not JSON because the keys and values are enclosed by single-quotes. The function ast.literal_eval can be used to parse this string into a Python dictionary.
import ast
str1 = "{'a':'1', 'b':'2'}"
d = ast.literal_eval(str1)
d["a"] # output is "1"
Other answers like https://stackoverflow.com/a/58540688/5666087 and https://stackoverflow.com/a/58540879/5666087 were able to use the json library because they changed str1 from "{'a':'1', 'b':'2'}" to '{"a":"1", "b":"2"}'. The former is invalid JSON, whereas the latter is valid JSON.