I pass the following json via command prompt as
$python new.py {'scenarioId':'null','scenarioName':'EC_02','scenarioDesc':'EC_02','riskEngine':'null'}
and when I run the following:
import sys
import json
str_json = sys.argv[1].replace("'", '"')
try:
d = json.dumps(str_json)
dat = json.loads(b)
print("Stress JSON is as follows \n",dat)
except json.decoder.JSONDecodeError:
print("Not a valid JSON")
print(dat['scenarioId'])
It's a valid json but I get the error TypeError: string indices must be integers for the last line.
It works fine when I initialize it as str_json in the code itself.
How to solve this?
In your code when you are using a_json = json.loads(b), here type of b variable is still string, convert it into json: a_json = json.loads(json.loads(b))
Code:
import sys
import json
str_json = sys.argv[1].replace("'", '"')
try:
b = json.dumps(str_json)
a_json = json.loads(json.loads(b))
print("Stress JSON is as follows \n",a_json)
except json.decoder.JSONDecodeError:
print("Not a valid JSON")
print(a_json['scenarioId'])
Output:
Stress JSON is as follows
{'scenarioId': 'null', 'scenarioName': 'EC_02', 'scenarioDesc': 'EC_02', 'riskEngine': 'null'}
null
Related
I want to make a keystore of values in JSON. Everything should work through the arguments entered into the console. That is, the data is first written to a file, and then must be read from there.
Input: python storage.py --key key_name --value value_name
Output: python storage.py --key key_name
A function with arguments and a function with data entry work. But I had a problem with the file read function. I need to print the key by its value, or values if there are several.
The recorded JSON looks something like this:
{"key": "Pepe", "value": "Pepeyaya"}{"key": "PepeHug", "value": "KekeHug"}{"key": "Pepega", "value": "Kekega"}{"key": "Pepe", "value": "Keke"}
I tried reading the file like this:
data = json.loads(f.read())
But the error is exactly the same
In other similar topics I saw that the "dictionaries" in JSON are written to the list. I tried something like this:
data = json.loads([f.read()])
Result:
TypeError: the JSON object must be str, bytes or bytearray, not list
Also:
data = json.load([f])
Result:
AttributeError: 'list' object has no attribute 'read'
I tried to change the recording function, but I can't write everything to a pre-created dictionary, everything is written to the right of it. Something like this:
[]{"key": "Pepe", "value": "Pepeyaya"}{"key": "PepeHug", "value": "KekeHug"}{"key": "Pepega", "value": "Kekega"}{"key": "Pepe", "value": "Keke"}
Code:
import os
import tempfile
import json
import sys
def create_json(path):
with open(path, mode='a', encoding='utf-8') as f:
json.dump([], f)
def add(key, value, path):
with open(path, mode='a', encoding='utf-8') as f:
entry = {'key': key, 'value': value}
json.dump(entry, f)
def read(a_key, path):
read_result = ""
with open(path) as f:
data = json.load(f)
print(data)
my_list = data
for i in my_list:
for key, value in i.items():
if key == a_key:
read_result += value + ", "
print(value)
def main():
storage_path = os.path.join(tempfile.gettempdir(), 'storage.json')
if sys.argv[1] == "--key":
arg_key = sys.argv[2]
if len(sys.argv) <= 3:
read(arg_key, storage_path)
elif sys.argv[3] == "--value":
arg_value = sys.argv[4]
add(arg_key, arg_value, storage_path)
else:
print("Введите верные аргументы")
else:
print("Введите верные аргументы")
if __name__ == '__main__':
main()
In general, from the attached code, now this error:
json.decoder.JSONDecodeError: Extra data: line 1 column 39 (char 38)
I need on request:
python storage.py --key Pepe
Get Pepe and PepeYaya values
this it's a basic storage method, this method is very bad for large json files but it's an example that show how can you do the job.
import os
import sys
import json
# storage.py key_name value
key =sys.argv[1]
value = sys.argv[2]
data_path = "data.json"
if os.path.isfile(data_path):
with open("data.json") as target:
json_data = json.load(target)
else:
json_data = {}
json_data[key] = value
with open("data.json", "w") as target:
json.dump(json_data, target)
in your case the problem is because the append flag when you open the file. If you need to write a new object you need to delete the last '}' of the json and add a ",object" item after that add the '}' char again.
I am trying to replace the value of varaible in json object but I am not able to do so.I want to replace the value of a datetime in json_input varaible but as of now datetime is getting concatenated
json_input='{"provider_code":"test","provider_resource_id":{"name":"test","value":"test"},"provider_account":"123","kpis":[{"kpi":"kpis","value":"80","unit":"%","datetime":""}]}'
newjson = {}
try:
decoded = json.loads(json_input)
# Access data
for x in decoded['kpis']:
if not (x['datetime']):
x['datetime']="2019-07-05T18:17:08.257Z"
newjson=json_input+x['datetime']
except (ValueError, KeyError, TypeError):
print("JSON format error")
print(newjson)
*Actual*
new json = {"provider_code":"aws","provider_resource_id":{"name":"app_arn","value":"arn:aws:elasticbeanstalk:us-east-1:802878444238:application/mcms-eb-test"},"provider_account":"802878444238","kpis":[{"kpi":"aws.elasticbeanstalk.health_status","value":"80","unit":"%","datetime":""}]}2019-07-05T18:17:08.257Z
*Expected*
new json='{"provider_code":"test","provider_resource_id":{"name":"test","value":"test"},"provider_account":"123","kpis":[{"kpi":"kpis","value":"80","unit":"%","datetime":"2019-07-05T18:17:08.257Z"}]}'
Your problem seems to be that you're writing json_input to newjson, when you really want to be writing decoded to newjson, as decoded is the object that you're modifying. json_input never gets modified, it is only used to create the JSON representation in Python. Furthermore, the +x['datetime'] doesn't help with anything, and is probably what's causing that added datetime at the end of your newjson.
Instead of newjson=json_input+x['datetime'], try newjson = decoded.dumps().
import json
json_input = '{"provider_code":"test","provider_resource_id":{"name":"test","value":"test"},"provider_account":"123","kpis":[{"kpi":"kpis","value":"80","unit":"%","datetime":""}]}'
try:
decoded = json.loads(json_input)
# Access data
for item in decoded['kpis']:
if not item['datetime']:
item['datetime'] = "2019-07-05T18:17:08.257Z"
except (ValueError, KeyError, TypeError):
print("JSON format error")
print(decoded)
I am trying to convert an XML file to MarkDown but I can't find an example of converting a python dict. Here is my code:
import pypandoc
import xmltodict
import json
datadict = open("/home/.../FIX44.xml")
dic = xmltodict.parse(datadict.read())
jsondump = json.dumps(dic)
#print jsondump
output = pypandoc.convert(jsondump, 'md', format='json', outputfile = 'test.md')
assert output == ""
When I try to run this I get:
RuntimeError: Pandoc died with exitcode "1" during conversion
Actually,I am new to json-python, and i am getting error of simplejson.scanner.jsondecodeerror:expecting value Expecting value: line 1 column 1 (char 0), i am trying for ["series"]["TimeStamp"] data
import urllib
import simplejson
response = urllib.urlopen("http://chartapi.finance.yahoo.com/instrument/1.0/RUSHIL.NS/chartdata;type=quote;range=5d/json")
#response.read() //this works
data = simplejson.loads(response)
print data //error
I found that your data has some unnecessary words. Response has 'finance_charts_json_callback(' at the first of data. So you should remove this function string. The following code shows.
import urllib
import simplejson
response = urllib.urlopen("http://chartapi.finance.yahoo.com/instrument/1.0/RUSHIL.NS/chartdata;type=quote;range=5d/json")
a = response.read()
a = a[29:-1] # remove function wrap
data = simplejson.loads(a)
print(data)
I'm not sure why this happen, there are zero length in my json file.
0
I t supposedly to be like this,
1000
I'm afraid the comma thing after each json object cause this issue. (My current json format)
{ A:"A"},{ B:"B"),...
The correct way is like this
{ A:"A"} { B:"B"),...
So how I can calculate all the length without removing the comma?
My code
import json
githubusers_data_path = 'githubusers.json'
githubusers_data = []
githubusers_file = open(githubusers_data_path, "r")
for line in githubusers_file:
try:
data = json.loads(line)
githubusers_data.append(data)
except:
continue
print len(githubusers_data)
Sample
{
"login": "datomnurdin"
}, {
"login": "ejamesc"
},...
I think you're getting an exception that you're suppressing with try-except, because of the commas.
One solution would be to convert your file to a string first, stick a '[' and ']' around the string to convert it into a valid json format, then use json.loads to convert the string.
import json
githubusers_data_path = 'githubusers.json'
githubusers_file = open(githubusers_data_path, "r")
githubusers_string = ''.join(line for line in githubusers_file)
githubusers_string = '[{}]'.format(githubusers_string)
githubusers_data = json.loads(githubusers_string)
print len(githubusers_data)
githubusers_file.close()
there is an exception in your code:
import json
githubusers_data_path = 'githubusers.json'
githubusers_data = []
githubusers_file = open(githubusers_data_path, "r")
for line in githubusers_file:
try:
data = json.load(githubusers_file) # exception from here
githubusers_data.append(data)
except Exception, e:
print e
print len(githubusers_data) # so githubusers_data is always []
Mixing iteration and read methods would lose data