Add new Key to json by getting it from same json using python












-1















I have a json and I am writing the content as CSV file.In the json, the key 'latitude' is a list and it contains null or two keys('Time','Rate') and values. While writing as csv, I want to add new columns instead of 'latitude' column. Columns Like,




  1. latitude_time -get value of Time inside the list/ null if no value

  2. latitude_rate -get value of Rate inside the list/ null if no value


OR



if the new keys and values can be added in the JSON itself in replacement of Key 'latitude' - Then, the json can be written as CSV



import json, csv

x="""[
{"longitude":"-73.689070","latitude":},
{"longitude":"-73.689930","latitude":[{"Time":0,"Rate":"Hourly"}]}
]"""

rows = json.loads(x)
fieldnames = ['longitude', 'latitude']
with open('test.csv', 'wb+') as f:
dict_writer = csv.DictWriter(f, fieldnames=fieldnames)
dict_writer.writerow(dict(zip(fieldnames, fieldnames)))
dict_writer.writerows(rows)









share|improve this question


















  • 1





    Load JSON in a variable. Get value data for "latitude" key. Delete the key. Add new keys to the variable with relevant data. Dump the variable to get new JSON.

    – Nitin Pawar
    Jan 2 at 9:30
















-1















I have a json and I am writing the content as CSV file.In the json, the key 'latitude' is a list and it contains null or two keys('Time','Rate') and values. While writing as csv, I want to add new columns instead of 'latitude' column. Columns Like,




  1. latitude_time -get value of Time inside the list/ null if no value

  2. latitude_rate -get value of Rate inside the list/ null if no value


OR



if the new keys and values can be added in the JSON itself in replacement of Key 'latitude' - Then, the json can be written as CSV



import json, csv

x="""[
{"longitude":"-73.689070","latitude":},
{"longitude":"-73.689930","latitude":[{"Time":0,"Rate":"Hourly"}]}
]"""

rows = json.loads(x)
fieldnames = ['longitude', 'latitude']
with open('test.csv', 'wb+') as f:
dict_writer = csv.DictWriter(f, fieldnames=fieldnames)
dict_writer.writerow(dict(zip(fieldnames, fieldnames)))
dict_writer.writerows(rows)









share|improve this question


















  • 1





    Load JSON in a variable. Get value data for "latitude" key. Delete the key. Add new keys to the variable with relevant data. Dump the variable to get new JSON.

    – Nitin Pawar
    Jan 2 at 9:30














-1












-1








-1








I have a json and I am writing the content as CSV file.In the json, the key 'latitude' is a list and it contains null or two keys('Time','Rate') and values. While writing as csv, I want to add new columns instead of 'latitude' column. Columns Like,




  1. latitude_time -get value of Time inside the list/ null if no value

  2. latitude_rate -get value of Rate inside the list/ null if no value


OR



if the new keys and values can be added in the JSON itself in replacement of Key 'latitude' - Then, the json can be written as CSV



import json, csv

x="""[
{"longitude":"-73.689070","latitude":},
{"longitude":"-73.689930","latitude":[{"Time":0,"Rate":"Hourly"}]}
]"""

rows = json.loads(x)
fieldnames = ['longitude', 'latitude']
with open('test.csv', 'wb+') as f:
dict_writer = csv.DictWriter(f, fieldnames=fieldnames)
dict_writer.writerow(dict(zip(fieldnames, fieldnames)))
dict_writer.writerows(rows)









share|improve this question














I have a json and I am writing the content as CSV file.In the json, the key 'latitude' is a list and it contains null or two keys('Time','Rate') and values. While writing as csv, I want to add new columns instead of 'latitude' column. Columns Like,




  1. latitude_time -get value of Time inside the list/ null if no value

  2. latitude_rate -get value of Rate inside the list/ null if no value


OR



if the new keys and values can be added in the JSON itself in replacement of Key 'latitude' - Then, the json can be written as CSV



import json, csv

x="""[
{"longitude":"-73.689070","latitude":},
{"longitude":"-73.689930","latitude":[{"Time":0,"Rate":"Hourly"}]}
]"""

rows = json.loads(x)
fieldnames = ['longitude', 'latitude']
with open('test.csv', 'wb+') as f:
dict_writer = csv.DictWriter(f, fieldnames=fieldnames)
dict_writer.writerow(dict(zip(fieldnames, fieldnames)))
dict_writer.writerows(rows)






python python-2.7






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 2 at 9:25









mvszmvsz

166




166








  • 1





    Load JSON in a variable. Get value data for "latitude" key. Delete the key. Add new keys to the variable with relevant data. Dump the variable to get new JSON.

    – Nitin Pawar
    Jan 2 at 9:30














  • 1





    Load JSON in a variable. Get value data for "latitude" key. Delete the key. Add new keys to the variable with relevant data. Dump the variable to get new JSON.

    – Nitin Pawar
    Jan 2 at 9:30








1




1





Load JSON in a variable. Get value data for "latitude" key. Delete the key. Add new keys to the variable with relevant data. Dump the variable to get new JSON.

– Nitin Pawar
Jan 2 at 9:30





Load JSON in a variable. Get value data for "latitude" key. Delete the key. Add new keys to the variable with relevant data. Dump the variable to get new JSON.

– Nitin Pawar
Jan 2 at 9:30












1 Answer
1






active

oldest

votes


















3














you can iterate through rows and replace the latitude dict with required keys e.g.



import json, csv

x="""[
{"longitude":"-73.689070","latitude":},
{"longitude":"-73.689930","latitude":[{"Time":0,"Rate":"Hourly"}]}
]"""
rows = json.loads(x)
new_rows =
for row in rows:
latitude_time = None
latitude_rate = None
latitude = row['latitude']
if latitude:
latitude_time = latitude[0].get('Time', None)
latitude_rate = latitude[0].get('Rate', None)
row.pop('latitude')
row.update({'latitude_time' : latitude_time,'latitude_rate':latitude_rate })
row = {key:str(value) for key, value in row.items()}
new_rows.append(row)
print new_rows





share|improve this answer


























  • Thanks @Amit Nanaware!! But I get the output as unicode format. [{'latitude_rate': None, 'latitude_time': None, u'longitude': u'-73.689070'}, {'latitude_rate': u'Hourly', 'latitude_time': 0, u'longitude': u'-73.689930'}]

    – mvsz
    Jan 2 at 9:49











  • row = {key:str(value) for key, value in row.items()} add this line before new_row.append(row)

    – Amit Nanaware
    Jan 2 at 9:55











  • Thanks @Amit Nanaware

    – mvsz
    Jan 2 at 10:08











  • wecome :) plz accept my answer

    – Amit Nanaware
    Jan 2 at 10:10











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54003885%2fadd-new-key-to-json-by-getting-it-from-same-json-using-python%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














you can iterate through rows and replace the latitude dict with required keys e.g.



import json, csv

x="""[
{"longitude":"-73.689070","latitude":},
{"longitude":"-73.689930","latitude":[{"Time":0,"Rate":"Hourly"}]}
]"""
rows = json.loads(x)
new_rows =
for row in rows:
latitude_time = None
latitude_rate = None
latitude = row['latitude']
if latitude:
latitude_time = latitude[0].get('Time', None)
latitude_rate = latitude[0].get('Rate', None)
row.pop('latitude')
row.update({'latitude_time' : latitude_time,'latitude_rate':latitude_rate })
row = {key:str(value) for key, value in row.items()}
new_rows.append(row)
print new_rows





share|improve this answer


























  • Thanks @Amit Nanaware!! But I get the output as unicode format. [{'latitude_rate': None, 'latitude_time': None, u'longitude': u'-73.689070'}, {'latitude_rate': u'Hourly', 'latitude_time': 0, u'longitude': u'-73.689930'}]

    – mvsz
    Jan 2 at 9:49











  • row = {key:str(value) for key, value in row.items()} add this line before new_row.append(row)

    – Amit Nanaware
    Jan 2 at 9:55











  • Thanks @Amit Nanaware

    – mvsz
    Jan 2 at 10:08











  • wecome :) plz accept my answer

    – Amit Nanaware
    Jan 2 at 10:10
















3














you can iterate through rows and replace the latitude dict with required keys e.g.



import json, csv

x="""[
{"longitude":"-73.689070","latitude":},
{"longitude":"-73.689930","latitude":[{"Time":0,"Rate":"Hourly"}]}
]"""
rows = json.loads(x)
new_rows =
for row in rows:
latitude_time = None
latitude_rate = None
latitude = row['latitude']
if latitude:
latitude_time = latitude[0].get('Time', None)
latitude_rate = latitude[0].get('Rate', None)
row.pop('latitude')
row.update({'latitude_time' : latitude_time,'latitude_rate':latitude_rate })
row = {key:str(value) for key, value in row.items()}
new_rows.append(row)
print new_rows





share|improve this answer


























  • Thanks @Amit Nanaware!! But I get the output as unicode format. [{'latitude_rate': None, 'latitude_time': None, u'longitude': u'-73.689070'}, {'latitude_rate': u'Hourly', 'latitude_time': 0, u'longitude': u'-73.689930'}]

    – mvsz
    Jan 2 at 9:49











  • row = {key:str(value) for key, value in row.items()} add this line before new_row.append(row)

    – Amit Nanaware
    Jan 2 at 9:55











  • Thanks @Amit Nanaware

    – mvsz
    Jan 2 at 10:08











  • wecome :) plz accept my answer

    – Amit Nanaware
    Jan 2 at 10:10














3












3








3







you can iterate through rows and replace the latitude dict with required keys e.g.



import json, csv

x="""[
{"longitude":"-73.689070","latitude":},
{"longitude":"-73.689930","latitude":[{"Time":0,"Rate":"Hourly"}]}
]"""
rows = json.loads(x)
new_rows =
for row in rows:
latitude_time = None
latitude_rate = None
latitude = row['latitude']
if latitude:
latitude_time = latitude[0].get('Time', None)
latitude_rate = latitude[0].get('Rate', None)
row.pop('latitude')
row.update({'latitude_time' : latitude_time,'latitude_rate':latitude_rate })
row = {key:str(value) for key, value in row.items()}
new_rows.append(row)
print new_rows





share|improve this answer















you can iterate through rows and replace the latitude dict with required keys e.g.



import json, csv

x="""[
{"longitude":"-73.689070","latitude":},
{"longitude":"-73.689930","latitude":[{"Time":0,"Rate":"Hourly"}]}
]"""
rows = json.loads(x)
new_rows =
for row in rows:
latitude_time = None
latitude_rate = None
latitude = row['latitude']
if latitude:
latitude_time = latitude[0].get('Time', None)
latitude_rate = latitude[0].get('Rate', None)
row.pop('latitude')
row.update({'latitude_time' : latitude_time,'latitude_rate':latitude_rate })
row = {key:str(value) for key, value in row.items()}
new_rows.append(row)
print new_rows






share|improve this answer














share|improve this answer



share|improve this answer








edited Jan 2 at 9:56

























answered Jan 2 at 9:34









Amit NanawareAmit Nanaware

1,1561112




1,1561112













  • Thanks @Amit Nanaware!! But I get the output as unicode format. [{'latitude_rate': None, 'latitude_time': None, u'longitude': u'-73.689070'}, {'latitude_rate': u'Hourly', 'latitude_time': 0, u'longitude': u'-73.689930'}]

    – mvsz
    Jan 2 at 9:49











  • row = {key:str(value) for key, value in row.items()} add this line before new_row.append(row)

    – Amit Nanaware
    Jan 2 at 9:55











  • Thanks @Amit Nanaware

    – mvsz
    Jan 2 at 10:08











  • wecome :) plz accept my answer

    – Amit Nanaware
    Jan 2 at 10:10



















  • Thanks @Amit Nanaware!! But I get the output as unicode format. [{'latitude_rate': None, 'latitude_time': None, u'longitude': u'-73.689070'}, {'latitude_rate': u'Hourly', 'latitude_time': 0, u'longitude': u'-73.689930'}]

    – mvsz
    Jan 2 at 9:49











  • row = {key:str(value) for key, value in row.items()} add this line before new_row.append(row)

    – Amit Nanaware
    Jan 2 at 9:55











  • Thanks @Amit Nanaware

    – mvsz
    Jan 2 at 10:08











  • wecome :) plz accept my answer

    – Amit Nanaware
    Jan 2 at 10:10

















Thanks @Amit Nanaware!! But I get the output as unicode format. [{'latitude_rate': None, 'latitude_time': None, u'longitude': u'-73.689070'}, {'latitude_rate': u'Hourly', 'latitude_time': 0, u'longitude': u'-73.689930'}]

– mvsz
Jan 2 at 9:49





Thanks @Amit Nanaware!! But I get the output as unicode format. [{'latitude_rate': None, 'latitude_time': None, u'longitude': u'-73.689070'}, {'latitude_rate': u'Hourly', 'latitude_time': 0, u'longitude': u'-73.689930'}]

– mvsz
Jan 2 at 9:49













row = {key:str(value) for key, value in row.items()} add this line before new_row.append(row)

– Amit Nanaware
Jan 2 at 9:55





row = {key:str(value) for key, value in row.items()} add this line before new_row.append(row)

– Amit Nanaware
Jan 2 at 9:55













Thanks @Amit Nanaware

– mvsz
Jan 2 at 10:08





Thanks @Amit Nanaware

– mvsz
Jan 2 at 10:08













wecome :) plz accept my answer

– Amit Nanaware
Jan 2 at 10:10





wecome :) plz accept my answer

– Amit Nanaware
Jan 2 at 10:10




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54003885%2fadd-new-key-to-json-by-getting-it-from-same-json-using-python%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Monofisismo

Angular Downloading a file using contenturl with Basic Authentication

Olmecas