I want to make json from text file, and make list value of ['ids']
{"previous_cursor": 0, "previous_cursor_str": "0", "next_cursor": 1351473067174597097, "ids": [250718906, 66612533], "next_cursor_str": "1351473067174597097"} {"previous_cursor": -1351352880715992572, "previous_cursor_str": "-1351352880715992572", "next_cursor": 0, "ids": [113030689, 22020972], "next_cursor_str": "0"}
My code
import json
f = open('22580877','r')
data = f.read()
datalist = data.split('\n')
idslist = []
for i in datalist:
datadic = eval(i)
print(datadic['ids'])
idslist.extend(datadic['ids'])
datadic = {}
for j in idslist:
print(j)
f.close()
the error msg is
Traceback (most recent call last):
File "test.py", line 11, in <module>
datadic = eval(i)
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
I can't find my syntaxerror in my code. help me please!
It sounds like you've been handed a file with a jsonified string on each line of the file. From your error message I kinda wonder if your file is corrupt or not formatted the way you think it is. However, if I had been given the task you've supplied I'd do something like this...
import json, traceback
idslist = []
with open('22580877', 'r') as f:
data = f.read()
datalist = data.split('\n')
for idx, json_string in enumerate(datalist):
try:
json_obj = json.loads(json_string)
idslist.extend(json_obj['ids'])
except:
print "bad json on line {} with traceback:\n{}".format(idx+1, traceback.format_exc())
for id in idslist:
print(id)
Related
I'd like to ask what is the best way to replace specific line in multiple json files. In everyfile its the same line that needs to be replaced. enter image description here
import json
with open('3.json') as f:
data = json.load(f)
for item in data['attributes']:
item['value'] = item['value'].replace("Untitled", item['BgTest'])
with open('3.json', 'w') as d:
json.dump(data, d)
I tried this code I found but it keeps giving me an error:
"/Users/jakubpitonak/Desktop/NFT/Gnomes Collection/ART-GEN-TUTORIAL 2.0/bin/python" /Users/jakubpitonak/PycharmProjects/pythonProject1/update.py
Traceback (most recent call last):
File "/Users/jakubpitonak/PycharmProjects/pythonProject1/update.py", line 25, in <module>
item['value'] = item['value'].replace("Untitled", item['BgTest'])
KeyError: 'BgTest'
Process finished with exit code 1
So item['BgTest'] does not exist in the items you're iterating through. I think you want to replace the "Untitled" value with the value "BgTest". In that case, replace the for loop with the one below:
for item in data['attributes']:
if item['value'] == 'Untitled':
item['value'] = 'BgTest'
import json
with open('3.json') as f:
data = json.load(f)
for item in data['attributes']:
item['value'] = "Your value here"
with open('3.json', 'w') as d:
json.dump(data, d)
BgTest is not a valid key for the example you posted. If you only have that key in certain rows of the list you can not use it in the for loop.
I have this code.
import json
with open('data5.json', 'r') as myfile:
data = myfile.read()
data_2 = data.replace('[', ' ')
data_3 = data_2.replace(']', ' ')
print(data_3)
My variable data_3 is like that:
{"Manufacturer": "VMware, Inc.", "Model": "VMware7,1", "Name": "DC01"} , {"Index": "1", "IPAddress": "192.168.1.240,fe80::350e:d28d:14a5:5cbb" }
I want to parse this. I want to get the value of Manufacturer or Model or Name. After parsing i will save them into the database. How can i do it?
import json
with open('data5.json', 'r') as myfile:
data = json.load(myfile)
for i in data:
print(data['Name'])
I tried this code for getting Name.
It gives me error
Traceback (most recent call last):
File "C:\Users\DELL\AppData\Roaming\JetBrains\PyCharmCE2021.3\scratches\scratch_38.py", line 5, in <module>
print(data['Name'])
TypeError: list indices must be integers or slices, not str
Your data is json, so use the json library from the stdlib:
import json
with open('data5.json', 'r') as myfile:
data = json.load(myfile)
No need to do any manual parsing.
Hi Iam new to coding but want to learn I have written this cod that lets the user insert an input and that should later save it as a text file(.txt) with json and then later I want open file as (.txt) file to later be able to modify the information as needed.
When I save the user information the content of the file looks like this:
{"Titel": "kalle"}{"Titel": "peter"}{"Titel": "kim"}{"Titel": "sena"}
But when I want to open that file with this commando:
import json
with open('testtitel.txt') as f:
json_data = json.load(f)
print(json_data)
This text appears:
Traceback (most recent call last):
File "openjson.py", line 4, in <module>
json_data = json.load(f)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 19 (char 18)
What is wrong if somebody could show what needs to be changed and explain as Iam new to coding I will add the code as well.
enter code
import json
class infoCd():
def __init__(self, EnTitel):
self.EnTitel = EnTitel
# //load to json dic function sa simon
def make_dict(self):
the_dict = {"Titel":self.EnTitel}
return the_dict
def readFromDict(self, inputDict):
self.EnTitel = inputDict["Titel"]
def display_cd_details(self):
print(" Title: {} ".format(self.EnTitel))
def see_details(self):
with open('testtitel.txt') as json_file:
testtitel = json.load(json_file)
for p in testtitel:
print(p)
def save_cd_details(cd):
with open('testtitel.txt', 'a') as txtfile:
json.dump(cd.make_dict(), txtfile)
def insert_cd_details():
counter = 0
lista = []
while(True):
EnTitel = input("Insert a titel: ")
counter+=1
Cd = infoCd(EnTitel )
lista.append(Cd)
print(lista)
save_cd_details(Cd)
avslutaCd = input(" Do you still want to(j/n)")
if (avslutaCd == "j"):
print("JAAA")
else:
print("Nej")
break
return lista
a = insert_cd_details()
for cd in a:
cd
print(a)
// code to open
with open('testtitel.txt') as f:
json_data = json.load(f)
print(json_data)
here
The string you are trying to decode is not valid JSON. I think you want this instead:
[{"Titel": "kalle"}, {"Titel": "peter"}, {"Titel": "kim"}, {"Titel": "sena"}]
Not sure what about this is wrong. Trying to import a line, which is joined as a string, and then put that in a CSV... Hmm....
import csv
import io
import os
import sys
def putInCSV():
if os.stat("test_attacking_ips_spreadsheet.csv").st_size == 0:
temp = open("test_attacking_ips_spreadsheet.csv", 'wb')
tempwrite = csv.writer(temp)
tempwrite.writerow(["IP Address"]['Hostname']['AS Number']['AS Name']['Net Range']['CC']['Type']['Targets']['Last Seen']['Notes']['FW Block']['Signatures'])
#["IP Address"]['Hostname']['AS Number']['AS Name']['Net Range']['CC']['Type']['Targets']['Last Seen']['Notes']['FW Block']['Signatures']#
temp.close()
Read = open("test_attacking_ips_spreadsheet.csv", 'rb')
Append = open("test_attacking_ips_spreadsheet.csv", 'ab')
reader = csv.reader(Read)
writer = csv.writer(Append)
sweetness = len(list(reader))
fileName = ''.join(sys.argv[1:2])
if fileName == '':
fileName = raw_input('Input the file with extension\n>')
with open(fileName) as f:
for line in f:
line = ''.join(line)
if "|" in line:
findStop = line.index("|")
ASNum = line[:findStop]
if "-" not in ASNum:
ASLine = "AS" + ASNum
else:
ASLine = ''
remainder = line[findStop:]
findStop = remainder.index("|")
ipAdd = remainder[:findStop]
HSTNm = ''
remainder = line[findStop:]
findStop = remainder.index("|")
ASName = remainder[:findStop]
writer.writerow([ipAdd][HSTNm][ASLine][ASName])
putInCSV()
Anyone see my fault? I couldn't find a concise reason, as most people linked api info, but, I couldn't find info to help back up my research.
Traceback (most recent call last):
File "C:\Users\user\Documents\bulk_whois\PutInCSV.py", line 46, in <module>
putInCSV()
File "C:\Users\user\Documents\bulk_whois\PutInCSV.py", line 44, in putInCSV
writer.writerow([ipAdd][HSTNm][ASLine][ASName])
TypeError: list indices must be integers, not str
Those lines are plain wrong:
tempwrite.writerow(["IP Address"]['Hostname']['AS Number']['AS Name']['Net Range']['CC']['Type']['Targets']['Last Seen']['Notes']['FW Block']['Signatures'])
...
writer.writerow([ipAdd][HSTNm][ASLine][ASName])
The syntax to define a list is l = ["a", "b", "c"]
["IP Address"]['Hostname'] tries to extract the element of index 'Hostname' from the list ["IP Address"] and leads to your error.
Hello all I keep getting this error while making a small program to sort large CSV files out, below is my code and error, what am I doing wrong?
if selection:
for stuff in stuffs:
try:
textFile = open("output.txt",'w')
mycsv = csv.reader(open(stuff))
d_reader = csv.DictReader(mycsv)
headers = d_reader.fieldnames <-- Error happens here
if selection in headers:
placeInList = headers.index(selection)
#placeInList = selection.index(selection)
for selection in tqdm(mycsv, desc='Extracting column values...', leave = True):
textFile.write(str(selection[int(placeInList)])+'\n')
print 'Done!'
textFile.close()
sys.exit()
except IOError:
print 'No CSV file present in directory'
sys.exit()
else:
sys.exit()
And the error:
Traceback (most recent call last):
File "postcodeExtractor.py", line 27, in <module> headers = d_reader.fieldnames
File "C:\Python27\lib\csv.py", line 90, in fieldnames self._fieldnames = self.reader.next()
TypeError: expected string or Unicode object, list found
instead of
mycsv = csv.reader(open(stuff))
d_reader = csv.DictReader(mycsv)
you want
d_reader = csv.DictReader(open(stuff))
the first line is the problem.