Consider this code, which is understandably failing:
def testDataTransform():
source = 'data/threads/testFile2.json'
newFile = 'data/threads/testFile1.json'
jX = returnJson(source)
jY = returnJson(newFile)
for dataL1 in jX:
#print dataL1['city']
for dataL2 in jY:
if dataL1['city'] == dataL2['city']:
dataL2.append(dataL1['population'])
print dataL2
# end testDataTransform
def returnJson(source):
#Grab destination file json
try:
with open(source) as jsonFile: # Open and verify file is there
# load JSON object into memory
j = json.load(jsonFile)
return j
except Exception, e:
print e
raise
# end returnJson
testDataTransform()
The error generated is: AttributeError: 'dict' object has no attribute 'append'
, which I now understand is due to trying to use append on a file steam and thus appending my JSON incorrectly. The question is how would I do this correctly? I want to add population data, which is in the source
file.
JSON structure in testFiles look like this:
[
{
"city": "New York",
"lat": 20.1234,
"long": 32.09876
},
{
"city": "London",
"lat": 21.1234,
"long": 37.09876
},
{
"city": "New Jersey",
"lat": 10.1234,
"long": 30.09876
}
]
One has a "population" node and other does not. I want to copy that population data from one file to another. How is that done? I wonder if converting the file stream into an array would help, but how do I even do that?
Thanks.
The error message is telling you exactly what's wrong. It's in this line
dataL2.append(dataL1['population'])
dataL2 is a dict(), and dict() does not have a method called append
What you want is
dataL2["population"] = dataL1['population']
Basically, the call to json.load()
for this file returns a list of dicts(). JSON arrays map to Python lists, JSON objects map to Python dictionaries. To add a new key to a dict, simply set a value on it.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다