I am new to python and i am working with some geojson files that contain a multiple objects each object represents a precinct. I need to print the coordinates for all of the precints how can i do this? i was trying this but it does not work:
import json
with open('districts and precinc data merged.json') as f:
data = json.load(f)
for i in json['features']:
print(i['geometry']['coordinates'])
this is an example of the json file:
{"type":"FeatureCollection", "features": [
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[552346.2856999999,380222.8998000007]]]]},"properties":{"OBJECTID":1,"STFID":"55001442500001","NAME":"0001"}},
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[529754.7249999996,409135.9135999996],[529740.0305000003,408420.03810000047]]]},"properties":{"OBJECTID":2,"STFID":"55001537250001","NAME":"0001","COUSUBFP":"53725"}},
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[508795.9363000002,441655.3672000002],[508813.49899999984,441181.034]]]},"properties":{"OBJECTID":6278,"STFID":"55141885750001","NAME":"0001","COUSUBFP":"88575"}}
]}
my desired output would be a for each line have the cordinates for each object like so:
[552346.2856999999,380222.8998000007]
[529754.7249999996,409135.9135999996],[529740.0305000003,408420.03810000047]
[508795.9363000002,441655.3672000002],[508813.49899999984,441181.034]
thank you for your help!
You have an error in your json. In first line you have 3 list open [[[ but closing 4 ]]]]. In your json file, replace [[[552346.2856999999,380222.8998000007]]]] with [[[552346.2856999999,380222.8998000007]]].
Then you can use nested loop,
x = {"type":"FeatureCollection", "features": [
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[552346.2856999999,380222.8998000007]]]},"properties":{"OBJECTID":1,"STFID":"55001442500001","NAME":"0001"}},
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[529754.7249999996,409135.9135999996],[529740.0305000003,408420.03810000047]]]},"properties":{"OBJECTID":2,"STFID":"55001537250001","NAME":"0001","COUSUBFP":"53725"}},
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[508795.9363000002,441655.3672000002],[508813.49899999984,441181.034]]]},"properties":{"OBJECTID":6278,"STFID":"55141885750001","NAME":"0001","COUSUBFP":"88575"}}
]}
for i in x["features"]:
for j in i["geometry"]["coordinates"][0]:
print(j, end=",") # replace `\n` with `,`
print("\b") # removes trailing ,
# output,
[552346.2856999999, 380222.8998000007]
[529754.7249999996, 409135.9135999996],[529740.0305000003, 408420.03810000047]
[508795.9363000002, 441655.3672000002],[508813.49899999984, 441181.034]
Related
I am trying to write data from json file to CSV file using python. My code is like this:
CSVFile1 = open('Group_A_participant_1_1.csv', 'a')
writeCSV1 = csv.writer(CSVFile1)
for file in data['annotations'][3]['instances']:
var = file['arguments'].get('argument1')
writeCSV1.writerow(var)
CSVFile.close()
My output is:
So my problem is that I can not see the whole word in one cell.
Thanks your helps inn advance!
I expect to get each word in one single cell.
Change
writeCSV1.writerow(var)
to
writeCSV1.writerow([var])
so you're writing an one-item list with your var instead of having the CSV module interpret var, a string, as separate characters.
For instance:
import csv
import sys
writeCSV1 = csv.writer(sys.stdout)
data = {
"annotations": [
{},
{},
{},
{
"instances": [
{"arguments": {"argument1": "foo"}},
{"arguments": {"argument1": "bar"}},
]
},
],
}
for file in data["annotations"][3]["instances"]:
var = file["arguments"].get("argument1")
writeCSV1.writerow([var])
prints out
foo
bar
whereas taking the brackets out from around [var] results in
f,o,o
b,a,r
as you described.
Click on the first cell of the column where you want the converted
names to appear (B2).
Type equal sign (=), followed by the text “Prof. “, followed by an
ampersand (&).
Select the cell containing the first name (A2).
Press the Return Key.
You will notice that the title “Prof.” is added before the first name in the list.
I have such json file:
[{
"datafiles": ["data.data"]
}]
Description in .proto file:
message Dataset {
repeated string datafiles = 1;
}
When I create a Dataset (Dataset(datafiles=datafiles)) object datafiles sets up in strange manner:
datafiles: "d"\ndatafiles: "a"\ndatafiles: "t"\ndatafiles: "a"\ndatafiles: ."\ndatafiles: "d"\ndatafiles: "a"\ndatafiles: "t"\ndatafiles: "a"
How to set it in correct way:
datafiles: "data.data"
It looks like your string ("data.data") is being iterated and added one character at a time.
This suggests that you are probably passing in a string by itself:
"data.data"
when you should really be passing in an iterable containing strings:
[ "data.data" ]
Try printing the value of datafiles right before your call to create the Dataset:
print(repr(datafiles))
... whatever ... Dataset(datafiles=datafiles)
My json file looks like this:
{"07/01/2015-08/01/2015":
{"ABC": [
["12015618727", "2015-07-29 02:32:01"],
["12024079732", "2015-07-24 13:04:01"],
["12024700142", "2015-07-02 00:00:00"]
]
}
}
I want to extract the numbers 12015618727, 12024079732, 12024700142 from here in python.
I wrote this code:
import json
numbers=set()
input_file=open('filename', 'r')
json_decode=json.load(input_file)
for item in json_decode["07/01/2015-08/01/2015"]["ABC"]:
for j in item:
numbers.add(j[0])
print " ".join(str(x) for x in numbers)
But this doesn't print the numbers.
Python has a json parsing library, see https://docs.python.org/2/library/json.html for details.
Usage:
import json
text = open("file.txt", "r").read()
obj = json.loads(text)
where obj is a python native dict object with nested arrays and dicts.
Edit:
This is the code you want.
import json
numbers=set()
input_file=open('filename.json', 'r')
json_decode=json.load(input_file)
for item in json_decode["07/01/2015-08/01/2015"]["ABC"]:
numbers.add(item[0])
print " ".join(str(x) for x in numbers)
You iterated through each item (the two strings) and added the first letter of each string, hence 1 and 2. Next time, please provide the output you got.
Also, you should attempt to debug your code first. I added a print at the beginning of each loop, and that made the problem pretty clear.
I am trying to write a code in python and deploy on google app engine. I am new to both these things. I have json which contains the following
[
{
"sentiment":-0.113568,
"id":455908588913827840,
"user":"ANI",
"text":"Posters put up against Arvind Kejriwal in Varanasi http://t.co/ZDrzjm84je",
"created_at":1.397532052E9,
"location":"India",
"time_zone":"New Delhi"
},
{
"sentiment":-0.467335,
"id":456034840106643456,
"user":"Kumar Amit",
"text":"Arvind Kejriwal's interactive session with Varansi Supporter and Opponent will start in short while ..Join at http://t.co/f6xI0l2dWc",
"created_at":1.397562153E9,
"location":"New Delhi, Patna.",
"time_zone":"New Delhi"
},
I am trying to load this data in python. I have the following code for it
data = simplejson.load(open('data/convertcsv.json'))
# print data
for row in data:
print data['sentiment']
I am getting the following error - TypeError: list indices must be integers, not str
If I uncomment the print data line and remove the last 2 lines I can see all the data in console. I want to be able to do some computations on the sentiment and also search for some words in the text. But for that I need to know how to get it line by line.
If you'd like to clean it up a bit
import json
with open('data/convertcsv.json') as f:
data = json.loads(f.read())
for row in data:
print row['sentiment']
The 'with' only leaves the file open as its used, then closes it automatically once the indented block under is executed.
Try this:
import json
f = open('data/convertcsv.json');
data = json.loads(f.read())
f.close()
for row in data:
print row['sentiment']
The issue is that you use data['sentiment'] instead of row['sentiment'] otherwise your code is fine:
with open('data/convertcsv.json', 'rb') as file:
data = simplejson.load(file)
# print data
for row in data:
print row['sentiment'] # <-- data is a list, use `row` here
I am using python to delete and update a JSON file generated from the data provided by user, so that only few items should be stored in the database. I want to delete a particular object from the JSON file.
My JSON file is:
[
{
"ename": "mark",
"url": "Lennon.com"
},
{
"ename": "egg",
"url": "Lennon.com"
}
]
I want to delete the JSON object with ename mark.
As I am new to python I tried to delete it by converting objects into dict but it is not working. Is there any other way to do it?
i tried this one:
index=0
while index < len(data):
next=index+1
if(data[index]['ename']==data[next]['ename']):
print "match found at"
print "line %d and %d" %(next,next+1)
del data[next]
index +=1
Here's a complete example that loads the JSON file, removes the target object, and then outputs the updated JSON object to file.
#!/usr/bin/python
# Load the JSON module and use it to load your JSON file.
# I'm assuming that the JSON file contains a list of objects.
import json
obj = json.load(open("file.json"))
# Iterate through the objects in the JSON and pop (remove)
# the obj once we find it.
for i in xrange(len(obj)):
if obj[i]["ename"] == "mark":
obj.pop(i)
break
# Output the updated file with pretty JSON
open("updated-file.json", "w").write(
json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
)
The main point is that we find the object by iterating through the objects in the loaded list, and then pop the object off the list once we find it. If you need to remove more than one object in the list, then you should store the indices of the objects you want to remove, and then remove them all at once after you've reached the end of the for loop (you don't want to modify the list while you iterate through it).
The proper way to json is to deserialize it, modify the created objects, and then, if needed, serialize them back to json.
To do so, use the json module. In short, use <deserialized object> = json.loads(<some json string>) for reading json and <json output> = json.dumps(<your object>) to create json strings.
In your example this would be:
import json
o = json.loads("""[
{
"ename": "mark",
"url": "Lennon.com"
},
{
"ename": "egg",
"url": "Lennon.com"
}
]""")
# kick out the unwanted item from the list
o = filter(lambda x: x['ename']!="mark", o)
output_string = json.dumps(o)
Your json file contains in a list of objects, which are dictionaries in Python. Just replace the list with a new one that doesn't have the object in it:
import json
with open('testdata.json', 'rb') as fp:
jsondata = json.load(fp)
jsondata = [obj for obj in jsondata if obj['ename'] != 'mark']
print(json.dumps(jsondata, indent=4))
You need to use the json module. I'm assuming python2. Try this:
import json
json_data = json.loads('<json_string>')
for i in xrange(len(json_data)):
if(json_data[i]["id"] == "mark"):
del json_data[i]
break
You have a list there with two items, which happen to be dictionaries. To remove the first, you can use list.remove(item) or list.pop(0) or del list[0].
http://docs.python.org/2/tutorial/datastructures.html#more-on-lists