I'm trying to add a new key to a JSON file, but I'm not having much success with it. The JSON file is one dictionary with a whole bunch of dictionaries nested in there. I'm trying to pass a new key and value at the same time to all those nested dictionaries like this:
with open("booksset1.json") as books:
bookData = json.load(books)
with open("booksset1.json", "w") as books:
init = 0
for book in bookData["books"]:
bookData["books"][init]["ISBN"] = init
init += 1
json.dump(bookData, books, indent=4)
But when I execute this code, this error shows up.
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I'm not quite sure what is going wrong here. Does anyone know what is going wrong?
Related
I am new to JSON file and i'm strugeling to get any information out of it.
The structure of the JSON file is as following:
Json file Structure
Now what I need is to access the "batches", to get the data from each variable.
I did try codes (shown below) i've found to reach deeper keys but somehow i still didnt get any results.
1.
def safeget(dct, *keys):
for key in keys:
try:
dct = dct[key]
except KeyError:
return None
return dct
safeget(mydata,"batches")
def dict_depth(mydata):
if isinstance(mydata, dict):
return 1 + (max(map(dict_depth, mydata.values()))
if mydata else 0)
return 0
print(dict_depth(mydata))
The final goal then would be to create a loop to extract all the information but thats something for the future.
Any help is highly appreciated, also any recommendations how i should ask things here in the future to get the best answers!
As far as I understood, you simply want to extract all the data without any ordering?
Then this should work out:
# Python program to read
# json file
import json
# Opening JSON file
f = open('data.json',)
# returns JSON object as
# a dictionary
data = json.load(f)
# Iterating through the json
# list
for i in data['emp_details']:
print(i)
# Closing file
f.close()
I am trying to print the number after quantity in the following JSON:
app_data : {
quantity: 1,
...
...
}
This is the link where I am trying to print
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(executable_path=os.path.abspath("chromedriver"), options=chrome_options)
inv = "https://steamcommunity.com/profiles/76561198404652782/inventory/json/440/2"
with urllib.request.urlopen(inv) as url:
data = json.loads(url.read().decode())
result = data.find('quantity')
print(data, result)
print(data)
Also tried .find() but no success
json.loads() returns a dictionary, and a dictionary does not have a find() method on it. Also, what the request returns is a nested dictionary, so a direct key lookup won't work. You may have to try something like what's been suggested in these earlier posts.
Find all occurrences of a key in nested python dictionaries and lists
How can I search for specific keys in this nested dictionary in Python?
You are searching for a key, So just use a condition for it..
if 'quantity' in data:
print data['quantity']
Folks,
I just spent a good amount of time trying to look this up -- I ought to be missing something basic.
I have a python object, all I want to do is to insert this object in mondodb.
This is what I have:
from pymongo import Connection
import json
conn = Connection()
db = conn.cl_database
postings = db.postings_collection
class Posting(object):
def __init__(self, link, found=None, expired=None):
self.link = link
self.found = found
self.expired = expired
posting = Posting('objectlink1')
value = json.dumps(posting, default=lambda x:x.__dict__)
postings.insert(value)
throws this error:
Traceback (most recent call last):
File "./mongotry.py", line 21, in <module>
postings.insert(value)
File "build/bdist.macosx-10.7-intel/egg/pymongo/collection.py", line 302, in insert
File "build/bdist.macosx-10.7-intel/egg/pymongo/database.py", line 252, in _fix_incoming
File "build/bdist.macosx-10.7-intel/egg/pymongo/son_manipulator.py", line 73, in transform_incoming
TypeError: 'str' object does not support item assignment
Seems like it is because json.dumps() returns a string.
Now if I do do a loads of the value before inserting it works fine:
posting = Posting('objectlink1')
value = json.dumps(posting, default=lambda x:x.__dict__)
value = json.loads(value)
postings.insert(value)
What is the most straight-forward to do this?
Thanks!
What is value in your initial code?
It should be dict not class instance
This should work:
postings.insert(posting.__dict__)
You are misusing the insert method for the collection. Review here: http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert
What you need to be inserting is a document. It should be a dict with keys and values. Simply trying to insert a string is not appropriate. json.dumps returns a string in json format. If you are just dumping it to get a dict then the json step is not necessary.
Insert exactly how your documents should look:
postings.insert({"key":"value"})
Or convert your class instance directly into the dict you want to store as a doc and then insert it. It works with your json.dumps.loads() because that ultimately does give you a dict.
I have a WS using Flask/python 2.7. I have 1 JSON object passed to the WS. I have been successful in capturing the object and returning the whole JSON.
I have looked all over for examples (many use print of test dataset in python) and have tried json.dumps, json.loads, json.dump, json.load, for loops, etc.
What I would like to do seems simple and I know it is me, but I get errors no matter what I try. I am trying to parse the JSON, put the values in to variables, and do "stuff".
This works:
#app.route('/v1/test', methods = ['POST'])
def api_message():
if request.headers['Content-Type'] == 'application/json':
return "JSON Message: " + json.dumps(request.json, separators=(',',':'))
else:
return "415 Unsupported Media Type"
This does not (and many variations of this using different things):
jsonobject = json.dumps(request.json)
pstring = json.loads(jsonobject)
for key, value in pstring.iteritems():
return value
What I want to do (pseudo code):
for each JSON
get the name value pairs in to a place where I can do something like this (which was done on a flat file)
input_data = pd.read_csv(sio, delimiter=',', names=columns)
probs = model.predict_proba(input_data)
I am sure I didn't make this as clear as I could but it is a challenge because I get errors like below (examples -- not all at once of course) with all the different things I try:
AttributeError: 'dict' object has no attribute 'translate'
TypeError: 'dict' object is not callable
AttributeError: 'str' object has no attribute 'iteritems'
So after all that, what is the right way to do this?
I'd like to add a dictionary to another dictionary in swift but I get the following error.
My aim is to mirror the structure of a nested object into a dictionary so that I am able to serialize it to JSON.
func toDictionary() -> Dictionary<String,AnyObject>{
var dic = Dictionary<String,AnyObject>()
println(From.Text)
println(From.Email)
var fromDic = ["Address":From.Email,"Text":From.Text]
println(fromDic)
dic.updateValue(fromDic, forKey: "From")
the code you show works fine for me - the error is likely not on that line xcode shows.
xcode6 often misses the correct line and the real error is some lines below
Assuming you have declarations for From, From.Email and From.Text, then it appears to work fine: