"location" : null // this is not really an array it's a null object
"location" : [] // this is an empty array
It looks like this API returns null when there is no location defined - instead of returning an empty array, not too unusual really - but they should tell you if they're going to do this.
Answer from Matt Varblow on Stack Overflow"location" : null // this is not really an array it's a null object
"location" : [] // this is an empty array
It looks like this API returns null when there is no location defined - instead of returning an empty array, not too unusual really - but they should tell you if they're going to do this.
null is a legal value (and reserved word) in JSON, but some environments do not have a "NULL" object (as opposed to a NULL value) and hence cannot accurately represent the JSON null. So they will sometimes represent it as an empty array.
Whether null is a legal value in that particular element of that particular API is entirely up to the API designer.
Simply:
Copyjson.loads(request.POST.get('mydata', '{}'))
Or:
Copydata = json.loads(request.POST['mydata']) if 'mydata' in request.POST else {}
Or:
Copyif '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 -
Copyjson_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.
Modify your reader script to this:
with open('favoriteColor.json') as inFile:
try:
colors = json.load(inFile)
except ValueError:
colors = []
This attempts to load the file as a json. If it fails due to a value error, we know that this is because the json is empty. Therefore we can just assign colors to an empty list. It is also preferable to use the "with" construct to load files since it closes them automatically.
I wouldn't take the approach you're trying. I would instead json.dump a dictionary, eg:
d = {'var1': '123', 'var2': [1, 2, 3]}
json.dump(d, fileout)
Then use dict.get to default it to a suitable value:
json_dict = json.load(filein)
favColor = json_dict.get('favColor', [])
Then you still have compulsory values that can except if not present using [] notation.
Puts the logic of missing values in your code instead of the json parsers...
Let's say I have a JSON object like this:
{"Data":[{"key1":"value1"},{"key2":"value2"},
{}]
}
If I wanted a list to look as follows: ['value1', 'value2', '']. How would I go about pulling in that null JSON key/value? Is that possible?
Thank you!
You're misunderstanding how in works. in checks to see if a key exists in a dictionary, it does not index into a dictionary. That's what the square brackets do.
if 'title_jpn' in json_data['gmetadata'][0] is not "":
The above line will not evaluate as you expect. It should be.
if json_data['gmetadata'][0]['title_jpn'] is not "":
This can be further simplified because empty strings '' always evaluate to False in python. So instead of checking if the string is not empty, just check if it has any value at all like the following:
if json_data['gmetadata'][0]['title_jpn']:
If you're trying to guard against the fact that title_jpn might be optional and not always exist, you need to do two conditions in your if statement (which I think is what you were originally trying to do):
if 'title_jpn' in json_data['gmetadata'][0] and json_data['gmetadata'][0]['title_jpn']:
The above line first checks if the title_jpn key is present before trying to check if it's value is empty. This can be further simplified using the dictionary .get() method which allows you to supply a default.
if json_data['gmetadata'][0].get('title_jpn', None):
The above will check if title_jpn is in the dictionary and return the value if it does, or None as a default if it does not. Since None is interpreted as False in python, the if block will not run, which is the desired behaviour.
dict.get(key, default=None)
However, since .get() automatically sets the default value to None, you can simply do the following.
if json_data['gmetadata'][0].get('title_jpn'):
Your .get won't work, since this applies to dictionaries. As far as I know, "In" won't work either since this is the syntax for a For loop. Probably you want the "Find" method, since this matches a substring within a longer string (which is your goal, if I understand correctly). It'll return minus one if the string isn't found. So in your case, example use:
if json_data['gmetadata'][0].find('title_jpn') != -1:
If you have a large number of null values that you want to change to empty array when using JSON#stringify, you can use a replace function (2nd param):
JSON.stringify(value[, replacer[, space]])
The function receives the key and the value, and you can decide, which value you want to return.
var data = {
var1: null,
var2: "someString",
var3: 1.3
};
var reslut = JSON.stringify(data, function(key, value) {
if (value === null) {
return [];
}
return value;
});
console.log(reslut);
To initialize an empty array in javascript simply write it like
var arr = [];
Example for JSON
var obj = {
arr: []
};
JSON.stringify(obj); // "{ "arr": [] }"
Check both, the key existence and its length:
import json, sys
obj=json.load(sys.stdin)
if not 'results' in obj or len(obj['results']) == 0:
exit(0)
else:
exit(1)
import json, sys
obj=json.load(sys.stdin)
if len(obj["results"])==0:
exit(0)
else:
exit(1)
try using the length of obj["results"]
You can try the below
data = {
"_class": "org.jenkinsci.plugins.workflow.job.WorkflowRun",
"actions": [
{
"date": "xyz",
"lastBuiltRevision": {
"branch": [
{
"SHA1": "5213affe970c86cd6e13b9d0e52515ac53f46aae",
"name": "feature/demo"
}
]
}
},
{
},
{
},
{
},
{
"date": "abc",
"lastBuiltRevision": {
"branch": [
{
"SHA1": "ca7972a32cc28304c22c98ceabf8e349fbf1a100",
"name": "refs/remotes/xyz/feature/demo_xyz"
}
]
}
},
{
"_class": "org.jenkinsci.plugins.displayurlapi.actions.RunDisplayAction"
},
{
"_class": "org.jenkinsci.plugins.pipeline.modeldefinition.actions.RestartDeclarativePipelineAction"
},
{
},
{
"_class": "org.jenkinsci.plugins.workflow.job.views.FlowGraphAction"
},
{
},
{
},
{
},
{
},
{
"_class": "org.marvelution.jji.export.ParentAction"
}
]
}
branch_name="refs/remotes/xyz/feature/demo_xyz"
data['actions'] = [x for x in data['actions'] if x and 'lastBuiltRevision' in x and x['lastBuiltRevision']['branch'][0]['name'] == branch_name]
for x in data.get('actions'):
entry = x['lastBuiltRevision']['branch'][0]
print(f'Name: {entry["name"]}, SHA1: {entry["SHA1"]}')
output
Name: refs/remotes/xyz/feature/demo_xyz, SHA1: ca7972a32cc28304c22c98ceabf8e349fbf1a100
Your code is absolutely okay, much better than example in answer you accepted. There're two ways to deal with such as cases: prevent exception or handle exception.
1. Prevent exception:
import json
with open('jenkinsBuild.json') as f:
data = json.load(f)
branch_name = 'refs/remotes/xyz/feature/demo_xyz'
for actions in data['actions']:
if 'lastBuiltRevision' in branch_data: # empty dict doesn't have this key too
for branch_data in actions['lastBuiltRevision']['branch']:
if branch_data['name'] == branch_name:
print('Name:', branch_data['name'], 'SHA1:', branch_data['SHA1'])
2. Handle exception:
import json
with open('jenkinsBuild.json') as f:
data = json.load(f)
branch_name = 'refs/remotes/xyz/feature/demo_xyz'
for actions in data['actions']:
try:
for branch_data in actions['lastBuiltRevision']['branch']:
if branch_data['name'] == branch_name:
print('Name:', branch_data['name'], 'SHA1:', branch_data['SHA1'])
except KeyError: # if any of accessed keys doesn't exist
pass
tweet is a string, you can't use it as a dictionary, you have to use json.loads:
tweet = json.loads(line) # no `json.dumps`
print tweet
tweet["sentiment"] = raw_input('provide input (sentiment): ') # error was here
tweets_data.append(tweet)
Currently the error is when you try to set a new field, but you use try .. except which goes to continue and you miss it completely. A step-through in the debugger would have solved it easily.
If you still want to use json.dumps use it AFTER you set fields in the dictionary.
you can also do the following after this line,
tweet = json.dumps(json.loads(line))
tweet = ast.literal_eval(tweet)
Don't forget to import ast,
import ast