How can I convert a dict to a JSON object? - python

I have a dict, ast that is stored as:
{u'databaseConnections': {u'shard1': {u'username': u'user'}}}
I want to convert this into JSON so I can do something like:
user = dbConf['databaseConnections']['shard1']['username']
I've tried using json.dumps(ast, ensure_ascii=False), but this just gives me the error:
print dbConf['databaseConnections']['shard1']['username']
TypeError: string indices must be integers
What am I doing wrong?

Converting this thing to JSON is unnecessary and counterproductive; you can just do
user = ast['databaseConnections']['shard1']['username']
with your ast dict directly. dicts are key-value mappings; JSON is text. You're trying to access your data as a key-value mapping, not serialize it and send it over the internet.

Related

Converting list with json dumps returns string instead of data dictionary

I am trying to get json data from Request URL using requests. Result I get is string so first I use json loads to convert it to list and after that I use json dumps to convert it to data dictionary. But instead I get string again. I would like to get it as data dictionary.
This is the code I use:
from json import loads
import json
url = 'https://www.sberbank.hr/umbraco/api/ExchangeRates/GetRates?dateString=1633159401811'
data = requests.get(url).json()
jsondata = loads(data)
print(type(jsondata))
data_dict = json.dumps(jsondata)
print(type(data_dict))
When you use json.loads, it converts thejson string to a dict type and json.dumps converts dict to json string.
Just use json.loads if you want a dict.
I've inspected the data you are using. The structure is:
List[Dict]
So you can acess it like this data[0] or any index.
It works exactly like how it described in the document: https://docs.python.org/3/library/json.html#json.dumps
I think your jsondata is already an array of objects, what are you trying to archive here?

Python TypeError: must be convertible to a buffer, not OrderedDict

I have used a Salesforce python package to query the API via SOAP, and it has returned me a base64 serialized ordered dict. How would I go about decoding this to an ordered dictionary?
Sounds like you want b64decode, followed by json.loads.

What is the type of a JSON object in python?

I'm new to JSON. I have a dictionary, I convert it to a JSON object using
myJsonObject = json.dumps(myDictionary)
But then If I check the type, I get <type 'str'>
Is string is the expected output for a JSON object?
PS: Python 2.7
Update: How can I get a JSON type, if dumps is not the correct way?
Of course, this is called "Serialization" - you are dumping a Python data structure into a JSON formatted string:
json.dumps()
Serialize obj to a JSON formatted str using this conversion table.
If you load a JSON string with loads(), this would be "deserialization" and you would get a Python list or a dictionary.
The N of JSON is for Notation ; it is, indeed, a data format specification. A JSON object is usually intended to be used as a storage or inter-process communication format. That's why it is in Python the universal flat format accepted by write() : a string object.
You can print it to screen, save it to a file, or communicate it to another program to verify it is correct and containing expected data.

Storing a nested dictionary of tuples in python

I have a dictionary of dictionaries that uses tuples as it's keys and values. I would like to write this dictionary and have tried json and pickle but neither of them seem to work. Is there a better alternative?
https://github.com/jgv7/markov-generator/blob/master/sentence-generator.py
json expects the key of the Key value pair to be a string or a number that can be properly converted to a string. bottom line - cant do a json.dumps on a dict with tuples as keys.
pickle should work unless the dictionary object is not properly serialized.
From your code:
with open(filename, 'rb') as df:
pickle.load(df)
print mapping
You don't bind the result of the load() call to a name, so that line has no effect (other than consuming processor time and moving the file pointer). That should read:
with open(filename, 'rb') as df:
mapping = pickle.load(df)
print mapping

storing python list into mysql and accessing it

How can I store python 'list' values into MySQL and access it later from the same database like a normal list?
I tried storing the list as a varchar type and it did store it. However, while accessing the data from MySQL I couldn't access the same stored value as a list, but it instead it acts as a string. So, accessing the list with index was no longer possible. Is it perhaps easier to store some data in the form of sets datatype? I see the MySQL datatype 'set' but i'm unable to use it from python. When I try to store set from python into MySQL, it throws the following error: 'MySQLConverter' object has no attribute '_set_to_mysql'. Any help is appreciated
P.S. I have to store co-ordinate of an image within the list along with the image number. So, it is going to be in the form [1,157,421]
Use a serialization library like json:
import json
l1 = [1,157,421]
s = json.dumps(l1)
l2 = json.loads(s)
Are you using an ORM like SQLAlchemy?
Anyway, to answer your question directly, you can use json or pickle to convert your list to a string and store that. Then to get it back, you can parse it (as JSON or a pickle) and get the list back.
However, if your list is always a 3 point coordinate, I'd recommend making separate x, y, and z columns in your table. You could easily write functions to store a list in the correct columns and convert the columns to a list, if you need that.

Categories