I try to read this ascii file with this json content with the following function:
{ "directory": { "name": "/wiki", "files": { "file": [ { "name": "/wiki/a.txt", "digest": "97d37a2ff85fbe35e1bf8ad38934d8fb518a6a3fbeb9b0b9305ce98e992f9dd2 " },
{ "name": "/wiki/d.txt", "digest": "ef91ee1257c3faa49f86f343cfec66010e5810e99db9f42e88774f90cd5b95d9 " },] } } }
def readJsonFile(path):
with open(path) as json_file:
json_data = json.load(json_file)
return json_data
I get this error of no JSON object could be decoded:
ValueError: No JSON object could be decoded
I tried with json.loads and I get the error:
TypeError: expected string or buffer
Am I using the right function?
The data is not a valid json (It has a trailing ,).
But it's a valid python literal; you can use ast.literal_eval instead:
import ast
def readJsonFile(path):
with open(path) as json_file:
return ast.literal_eval(json_file.read())
Your json string is wrong, as validated by jsonint:
Related
This is my output.json file:
{
"ParsedResults": [
{
"TextOverlay": {
"Lines": [],
"HasOverlay": false,
"Message": "Text overlay is not provided as it is not requested"
},
"TextOrientation": "0",
"FileParseExitCode": 1,
"ParsedText": "180 Grade IV\r\n\u0103\u021ar: Class VIII Pass\r\nwww.facebook.com, Since 2012\r\n",
"ErrorMessage": "",
"ErrorDetails": ""
}
],
"OCRExitCode": 1,
"IsErroredOnProcessing": false,
"ProcessingTimeInMilliseconds": "343",
"SearchablePDFURL": "Searchable PDF not generated as it was not requested."
}
I am trying to get the ParsedText value from this JSON file.
This is my the code I am using:
import json
f = open('output.json',)
data = json.load(f)
print(data['ParsedResults']['TextOverlay']['ParsedText'])
f.close()
Facing this error:
TypeError: list indices must be integers or slices, not str
How to read that particular value from ParsedText, please guide. Thanks in Advance
ParsedResults is not an object, it's a list
try this:
import json
f = open('output.json',)
data = json.load(f)
print(data['ParsedResults'][0]['ParsedText'])
f.close()
data['ParsedResults'] is a list, you need to use the index to parse, So you are getting TypeError: list indices must be integers or slices, not str
use data['ParsedResults'][0].
use the following,
import json
f = open('output.json',)
data = json.load(f)
print(data['ParsedResults'][0]['TextOverlay']['ParsedText'])
f.close()
how to convert using python below payloads:
{
"abc": {
"i": "1212",
"j": "add"
}
}
to
"{\n\n \"abc\": {\n \"i\": \"1212\",\n \"j\": \"add\"\n }\n}"
You can use the optional indent parameter of json.dump and json.dumps to add newlines and indent to the generated string.
>>> import json
>>> payload = {
... "assessmentstatus": {
... "id": "D37002079003",
... "value": "In-Progress"
... }
... }
...
>>> json.dumps(payload)
'{"assessmentstatus": {"id": "D37002079003", "value": "In-Progress"}}'
>>> json.dumps(payload, indent=0)
'{\n"assessmentstatus": {\n"id": "D37002079003",\n"value": "In-Progress"\n}\n}'
>>> json.dumps(payload, indent=2)
'{\n "assessmentstatus": {\n "id": "D37002079003",\n "value": "In-Progress"\n }\n}'
With properly displayed whitespace:
>>> print(json.dumps(payload, indent=2))
{
"assessmentstatus": {
"id": "D37002079003",
"value": "In-Progress"
}
}
It seems you actually want the string including the enclosing " and with all the " within the string escaped. This is surprisingly tricky using Python's repr, as it always tries to use either ' or " as the outer quotes so that the quotes do not have to be escaped.
What seems to work, though, is to just json.dumps the JSON string again:
>>> json.dumps(json.dumps(payload, indent=2))
'"{\\n \\"assessmentstatus\\": {\\n \\"id\\": \\"D37002079003\\",\\n \\"value\\": \\"In-Progress\\"\\n }\\n}"'
>>> print(json.dumps(json.dumps(payload, indent=2)))
"{\n \"assessmentstatus\": {\n \"id\": \"D37002079003\",\n \"value\": \"In-Progress\"\n }\n}"
Im assuming it has newlines since its in a file
with open('file.json') as f: data = json.load(f)
Then do what you want with the data
You can save data to a file in JSON format like this
import json
data = {
"assessmentstatus": {
"id": "D37002079003",
"value": "In-Progress"
}
}
with open("file.txt", "w") as file:
json.dump(data, file, indent=4)
To retrieve this data you can do
import json
with open("file.txt") as file:
data = json.load(file)
print(data)
JSON is a way to store store data in a string format and be able to parse that data to convert it to actual data.
So trying to convert "{\n\n "assessmentstatus": {\n "id": "D37002079003",\n "value": "In-Progress"\n }\n}" on your own is the wrong way to go at this, since JSON is great at doing this.
I searched for a long time but I am not really familiar with python and json and I can't find the answer of my problem.
Here is my Python script
import json
jsonFile = open("config.json", "r")
data = json.load(jsonFile)
data.format(friendly, teaching, leader, target)
print(data)
Here is json the file:
{
"commend": {
"friendly": {},
"teaching": {},
"leader": {}
},
"account": {
"username": "",
"password": "",
"sharedSecret": ""
},
"proxy": {
"enabled": false,
"file": "proxies.txt",
"switchProxyEveryXaccounts": 5
},
"type": "COMMEND",
"method": "SERVER",
"target": "https://steamcommunity.com/id/{}",
"perChunk": 20,
"betweenChunks": 300000,
"cooldown": 28800000,
"steamWebAPIKey": "{}",
"disableUpdateCheck": false
}
I tried .format but we can't use this method with with a dictionary.
With your help I managed to find the answer A big thank you for your speed and your help ! Here is what I did:
import json
jsonFile = open("config.json", "r")
data = json.load(jsonFile)
(data['commend']['friendly']) = nbfriendly
(data['commend']['teaching']) = nbteaching
(data['commend']['leader']) = nbleader
print(data)
print(data)
A json file is a dictionary, so you can use dict methods with it. Here is the code:
import json
with open("config.json", "r") as json_file:
data = json.load(json_file)
# Let's say you want to add the string "Hello, World!" to the "password" key
data["account"]["password"] += "Hello, World!"
# Or you can use this way to overwrite anything already written inside the key
data["account"]["password"] = "Hello, World!"
print(data)
You can add data by tranversing through it like a dictionary:
data['key'] = value
Example:
dic["commend"]["friendly"]={'a':1}
I've more then 1GB json file with encoded strings inside. For example:
{
"id": "3",
"billing_type": {
"id": "standard",
"name": "\u0421\u0442\u0430\u043d\u0434\u0430\u0440\u0442"
},
"area": {
"id": "1",
"name": "\u041c\u043e\u0441\u043a\u0432\u0430"
}
}
How I can decode like this \u041c\u043e string inside my json file in my case?
if you use python3, just import json will help.
import json
result = json.loads(json_data)
print(result)
or python2, you should use encode method for each values (after check type first)
result = json.loads(json_data)
for k, v in result.items():
if isinstance(v, dict):
for dk, dv in v.items():
print dk.encode("utf-8"), dv.encode("utf-8")
else:
print k.encode("utf-8"), v.encode("utf-8")
data = "\u041c\u043e\u0441\u043a\u0432\u0430"
data = data.encode().decode('unicode-escape')
This might be a solution.
I have the same json data in two forms - one is a one-liner, the second one is just formatted output.
JSON A:
{"id":1, "name":"BoxH", "readOnly":true, "children":[{ "id":100, "name":"Box1", "readOnly":true, "children":[ { "id":1003, "name":"Box2", "children":[ { "id":1019, "name":"BoxDet", "Ids":[ "ABC", "ABC2", "DEF2", "DEFHD", "LKK" ]}]}]}]}
and JSON B:
{
"id":1,
"name":"BoxH",
"readOnly":true,
"children":[
{
"id":100,
"name":"Box1",
"readOnly":true,
"children":[
{
"id":1003,
"name":"Box2",
"children":[
{
"id":1019,
"name":"BoxDet",
"Ids":[
"ABC",
"ABC2",
"DEF2",
"DEFHD",
"LKK"
]
}
]
}
]
}
]
}
Why is it, that the code:
import json
if open('input_file.json'):
output_json = json.load('input_file.json')
in case A throws
ValueError: No JSON object could be decoded
and the case B works correctly. I'm just wondering why is it so? I thought that the JSON A and JSON B are the same for json.load. What should I do to get the both cases working?
json.load accept a file object (not file path). And you should keep the file reference. Try following:
import json
with open('input_file.json') as f:
output_json = json.load(f)
Alternatively you can use json.loads which accept serialized json string:
import json
with open('input_file.json') as f:
output_json = json.loads(f.read())
Acutally in my case there was problem with coding. As soon as I've converted the one-liner-file to UTF-8 without BOM, it started to working without any problems. The coding before was ANSI. So.. lesson learned: check the file coding.