How can I create the empty json object? - python

I have this code
json.loads(request.POST.get('mydata',dict()))
But I get this error
No JSON object could be decoded
I just want that if don't have mydata in POST, then I don't get that error.

Simply:
json.loads(request.POST.get('mydata', '{}'))
Or:
data = json.loads(request.POST['mydata']) if 'mydata' in request.POST else {}
Or:
if 'mydata' in request.POST:
data = json.loads(request.POST['mydata'])
else:
data = {} # or data = None

loads() takes a json formatted string and turns it into a Python object like dict or list. In your code, you're passing dict() as default value if mydata doesn't exist in request.POST, while it should be a string, like "{}". So you can write -
json_data = json.loads(request.POST.get('mydata', "{}"))
Also remember, the value of request.POST['mydata'] must be JSON formatted, or else you'll get the same error.

Related

I want to convert a list of strings to a list of dictionaries

I stored a twitter data to a mysql db as a json. When I fetch it back, it returns a list of string instead of a list of dictionary. I am looking for a way turn it to a list of dictionaries. This is the format i get the stored data back. "tweetdata" is the column name in the db
[{"tweetdata":"[{\"text\":\"b problem\",\"len\":10,\"Date\":1583160242000,\"Source\":\"Twitter for
Android\",\"Likes\":0,\"RTs\":0},}]"}]
I want it to return something like this as a list of dicts with the column name stripped off
[{\"text\":\"b problem\",\"len\":10,\"Date\":1583160242000,\"Source\":\"Twitter for
Android\",\"Likes\":0,\"RTs\":0},}]
First of all, looks like you provided a wrong json format. Provided that you have a correct json format then you can use json loads function to load the the json data and convert it to dictionary type. Here is code snippet in python.
import json
json_data = '[{"tweetdata":[{\"text\":\"b problem\",\"len\":10,\"Date\":1583160242000,\"Source\":\"Twitter for Android\",\"Likes\":0,\"RTs\":0}]}]'
parsed_json = json.loads(json_data)
parsed_dict = parsed_json[0]['tweetdata'][0]
print(type(parsed_dict))
for item in parsed_dict.items():
print(item)
Above code snippet will print these.
<class 'dict'>
('text', 'b problem')
('len', 10)
('Date', 1583160242000)
('Source', 'Twitter for Android')
('Likes', 0)
('RTs', 0)
Try this:
if your data in tweetdata variable then tweetdata[0]["tweetdata"]
it'll return like this:
[{\"text\":\"b problem\",\"len\":10,\"Date\":1583160242000,\"Source\":\"Twitter for Android\",\"Likes\":0,\"RTs\":0},}]
actually you can do like this:
data = [{"tweetdata":"[{\"text\":\"b problem\",\"len\":10,\"Date\":1583160242000,\"Source\":\"Twitter for Android\",\"Likes\":0,\"RTs\":0},}]"}][0]["tweetdata"]
and print data you'll get the same result.

How to add an element to an empty JSON in python?

I created an empty string & convert it into a JSON by json.dump. Once I want to add element, it fails & show
AttributeError: 'str' object has no attribute 'append'
I tried both json.insert & json.append but neither of them works.
It seems that it's data type problem. As Python can't declare data type as Java & C can, how can I avoid the problem?
import json
data = {}
json_data = json.dumps(data)
json_data.append(["A"]["1"])
print (json_data)
JSON is a string representation of data, such as lists and dictionaries. You don't append to the JSON, you append to the original data and then dump it.
Also, you don't use append() with dictionaries, it's used with lists.
data = {} # This is a dictionary
data["a"] = "1"; # Add an item to the dictionary
json_data = json.dumps(data) # Convert the dictionary to a JSON string
print(json_data)

How do I take the specific value of a JSON formatted string?

Write a function named "get" that takes a JSON formatted string as a parameter in the format "{"attack": float, "decay": float, "sustain": float, "release": float}" and returns the value at the key "attack".
import json
def get(JSON):
load = json.loads(JSON)
dictionary = {}
attack = [f[0] for f in load]
attack1 = dictionary.update(attack)
for key, value in attack1.items():
if key == 'attack':
return value
My question is how do I take the specific value ('attack') in a JSON formatted string?
Once you've loaded it using json.loads(), you've converted it from a string to a dictionary. That means that the load variable you assign in load = json.loads(JSON) is already a dictionary, and you can access it using normal python dictionary syntax from there:
import json
def get(JSON):
load = json.loads(JSON)
return load["attack"]
So if your question is how to obtain the value of attack from JSON then do this:
load = json.loads(JSON)
load["attack"]
json.loads() makes the json into a python dictionary.

TypeError('list indices must be integers, not str',) with get() method in Python

I am trying to convert JSON files to CSV using below code. The PARENT_ID and PARENT_TYPE fields can be NULL most of the times. If I use result["parent"]["id"] it returns KeyError. That's why I thought of using get() to return whatever value they hold. But I am getting TypeError('list indices must be integers, not str',) for these fields. Can anyone suggest any workaround?
Thanks in advance!
"parent" is a list within "result" dict.
my_dict_list =[]
try:
for f in os.listdir(file_dir):
if f.endswith('.json') and f.startswith('folders_'):
file_path = os.path.join(file_dir, f)
data = open(file_path, 'r')
for line in data:
my_dict = {}
parsed_data = json.loads(line)
my_dict["REQUEST_ID"] = parsed_data["requestId"]
my_dict["SUCCESS"] = parsed_data["success"]
for result in parsed_data["result"]:
my_dict["NAME"] = result["name"]
my_dict["DESCRIPTION"] = result["description"]
my_dict["FOLDER_ID"] = result["folderId"]["id"]
my_dict["FOLDER_ID_TYPE"] = result["folderId"]["type"]
my_dict["FOLDER_TYPE"] = result["folderType"]
my_dict["PARENT_ID"] = result.get(["parent"]["id"])
my_dict["PARENT_TYPE"] = result.get(["parent"]["type"])
Currently you are trying to access the member "id" from a list with the string "parent" in the following line:
my_dict["PARENT_ID"] = result.get(["parent"]["id"])
You have to check if the result dict contains the key "parent".
The get method of your result dict can be used for this.
It returns None if the dict does not contain the key "parent".
Otherwise use the get method and try to get the id of the parent
Your code has to be
my_dict["PARENT_ID"] = result["parent"].get("id") if result.get("parent") else None

Getting Keyerror when parsing JSON in Python

I have just made a program to parse some data from an api. The api gives data back with a JSON format. When I try to parse it it gives me a key error
url = json.loads(r.text)["url"]
KeyError: 'url'
This is the part of the code
url = json.loads(r.text)["url"]
I am trying to get the data in the plain field. Here is the output from the API:
{"updates":[{"id":"a6aa-8bd","description":"Bug fixes and enhancemets","version":"8.1.30","type":"firmware","url":"https://con-man.company.com/api/v1/file-732e844b","updated":"2017-07-25"}]}
You cannot access url since it is inside update (list), therefore you need to Pass index and then key :
One liner:
>>> url = json.loads(r.text)['updates'][0]['url']
'https://con-man.company.com/api/v1/file-732e844b'
Explicit
>>> jobj = json.loads(r.text)
>>> url = jobj['updates'][0]['url']
'https://con-man.company.com/api/v1/file-732e844b'
try this,
url = json.loads(r.text)["updates"][0]["url"]
{
"updates": [
{
"id":"a6aa-8bd",
"description":"Bug fixes and enhancemets",
"version":"8.1.30",
"type":"firmware",
"url":"https://con-man.company.com/api/v1/file-732e844b",
"updated":"2017-07-25"
}
]
}
Try to visualize of your dict, it has only one key "update" in that key value it has another list and into that list, you has another dict
so if in your case
_dict = json.loads(r.text) # read file and load dict
_list = _dict['updates'] # read list inside dict
_dict_1 = _list[0] # read list first value and load dict
url = _dict_1['url'] # read 'url' key from dict
I used this and works now for me.
json_object = json.loads(response.content.decode("utf-8"))['list'][0]['localPercentDynamicObjectsUsed']

Categories

Resources