Getting "Method not found: 'Boolean Newtonsoft.Json.Schema.SchemaExtensions.IsValid" in VS2019 - json

I've copied a sample from the site https://www.newtonsoft.com/jsonschema/help/html/ValidatingJson.htm:
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
...
string schemaJson = #"{
'description': 'A person',
'type': 'object',
'properties': {
'name': {'type': 'string'},
'hobbies': {
'type': 'array',
'items': {'type': 'string'}
}
}
}";
JSchema schema = JSchema.Parse(schemaJson);
JObject person = JObject.Parse(#"{
'name': 'James',
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}");
bool valid = person.IsValid(schema);
// true
When I try to debug it in VS2019 I get an exception: "Method not found: 'Boolean Newtonsoft.Json.Schema.SchemaExtensions.IsValid"
I feel so stupid for asking, but what am I doing wrong?

Related

'Reader' object has no attribute 'tell' error with jsonlines and cloud storage

I'm writing a cloud function to extract data from an API in the following format:
[{'_id': '123qasd', 'description': 'stuff here', 'userId': 'xxxx', 'billable': False, 'taskId': 'asddf1234', 'projectId': '5e11gg55', 'timeInterval': {'start': '2020-05-16T09:00:00+02:00', 'end': '2020-05-16T13:00:00+02:00', 'duration': 14400}, 'taskName': 'Production', 'tags': [], 'isLocked': True, 'customFields': [], 'userName': 'Dupond', 'userEmail': 'stuff#mail.com', 'projectName': 'my project', 'projectColor': '#607D8B', 'clientName': 'my client', 'clientId': 'xxxxxxxx'}, {'_id': '123qasd', 'description': 'stuff here', 'userId': 'xxxx', 'billable': False, 'taskId': 'asddf1234', 'projectId': '5e11gg55', 'timeInterval': {'start': '2020-05-16T09:00:00+02:00', 'end': '2020-05-16T13:00:00+02:00', 'duration': 14400}, 'taskName': 'Production', 'tags': [], 'isLocked': True, 'customFields': [], 'userName': 'Dupond', 'userEmail': 'stuff#mail.com', 'projectName': 'my project', 'projectColor': '#607D8B', 'clientName': 'my client', 'clientId': 'xxxxxxxx'}, {'_id': '123qasd', 'description': 'stuff here', 'userId': 'xxxx', 'billable': False, 'taskId': 'asddf1234', 'projectId': '5e11gg55', 'timeInterval': {'start': '2020-05-16T09:00:00+02:00', 'end': '2020-05-16T13:00:00+02:00', 'duration': 14400}, 'taskName': 'Production', 'tags': [], 'isLocked': True, 'customFields': [], 'userName': 'Dupond', 'userEmail': 'stuff#mail.com', 'projectName': 'my project', 'projectColor': '#607D8B', 'clientName': 'my client', 'clientId': 'xxxxxxxx'}]
I want to send this data to Cloud Storage and then, read them with BigQuery. In order to do this I need to convert json to ndjson.
I'm using jsonlines to handle the conversion. Here is an extract of my function:
with jsonlines.open(f'/tmp/output.jsonl', "w") as writer:
writer.write(data)
date = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
bucket = storage_client.bucket(bucket_name)
destination_blob_name = '{}'.format(date)
blob = bucket.blob(destination_blob_name)
with jsonlines.open('/tmp/output.jsonl') as reader:
blob.upload_from_file(reader)
I have the following error 'Reader' object has no attribute 'tell'
What's wrong?
I managed to get it to work! use just normal file open.
with open('output.jsonl', 'rb') as f:
blob.upload_from_file(f)

remove k,v from http response in python

I am new to python and am struggling with remove a key and value from a json return by an http request. When querying a task I get the following back.
data = requests.get(url,headers=hed).json()['data']
[{
'gid': '12011553977',
'due_on': None,
'name': 'do something',
'notes': 'blalbla,
'projects': [{
'gid': '120067502445',
'name': 'Project1'
}]
}, {
'gid': '12002408815',
'due_on': '2021-10-21',
'name': 'Proposal',
'notes': 'bla',
'projects': [{
'gid': '12314323523',
'name': 'Project1'
}, {
'gid': '12314323523',
'name': 'Project2'
}, {
'gid': '12314323523',
'name': 'Project3'
}]
I am trying to remove 'gid' from all projects so projects look like this
'projects': [{
'name': 'Company'
}]
What is the best way to do this with python3?
You can use recursion to make a simpler function to handle all elements and sub-elements. I haven't done extensive testing, or included any error checking or exception handling; but this should be close to what you want:
def rec_pop(top_level_list,key_to_pop='gid'):
for item in top_level_list:
item.pop(key_to_pop)
for v in item.values():
if isinstance(v,list):
rec_pop(v)
# call recursive fn
rec_pop(data)
Result:
In [25]: data
Out[25]:
[{'due_on': None,
'name': 'do something',
'notes': 'blalbla',
'projects': [{'name': 'Project1'}]},
{'due_on': '2021-10-21',
'name': 'Proposal',
'notes': 'bla',
'projects': [{'name': 'project2'}]}]

Get "Bad Request" when using json api

I am trying to get a json post working using grails, and keep getting "bad request". I have stripped down everything to the point that the routine doesn't make much sense, but it is simple.
The api should return an error text requesting valid parameters...
You will be able to guess that I am pretty new to this, so any hints would be greatly appreciated.
Thanks...
def testit() {
def statusLine = "200"
def http = new HTTPBuilder( 'http://api.scribblepics.com' )
def postBody = [
'apiKey': 'test',
'sender': [
'firstName': 'First',
'lastName': 'Last',
'email': 'first.last#mail.com'
]
]
http.post( path: '/postcard/create', body: postBody,
requestContentType: URLENC ) { resp ->
println "status: ${resp.statusLine}"
statusLine = resp.statusLine
assert resp.statusLine.statusCode == 200
}
}
You are missing other mandatory parameters recipient, message, imageData.
Or have you already tried with these and are still getting the same error?
def postBody = [
'apiKey': 'test',
'sender': [
'firstName': 'First',
'lastName': 'Last',
'email': 'first.last#mail.com'
],
'recipient': [
'name': 'full name',
'addressLine1': 'Main Street',
'addressLine2': 'Main Street2',
'city': 'city',
'state': 'state',
'zip': '1234',
'country': 'country'
],
'message': 'A test message...',
'imageUrl':'http://www.google.ch/imgres?sa=X&biw=1680&bih=859&tbm=isch&tbnid=Dw_q5yUyBtrHAM%3A&imgrefurl=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FFerrari_F430&docid=sKowXM25Yu8uoM&imgurl=http%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2F1%2F17%2FFerrari_F430_front_20080605.jpg&w=2275&h=1160&ei=jsAJU9CHL6OK5AS7u4GQAw&zoom=1&ved=0CGUQhBwwAA&iact=rc&dur=2130&page=1&start=0&ndsp=18'
]

Cannot load stores using jsonp extjs4.1

I am trying to load ext data stores using jsonp. The below code is working fine when i am using ajax and making requests on the same domain.
The store definition:
var baseUrl = 'http://localhost:8090/';
Ext.define('Ktimatologio.store.NewWholeBlockStore', {
extend: 'Ext.data.Store',
alias: 'widget.newsingleblockstore',
requires: ['Ktimatologio.model.NewWholeBlockModel'],
model: 'Ktimatologio.model.NewWholeBlockModel',
groupField: 'search_tag',
fields: [
{name:'id', mapping:'id'},
{name:'id1', mapping:'id1'},
{name: 'text', mapping: 'text'},
{name: 'title', mapping: 'title'},
{name: 'fek', mapping: 'fek'},
{name: 'date', mapping: 'date'},
{name: 'descr', mapping: 'description'},
{name: 'model', mapping: 'model'},
{name: 'body', mapping: 'body'},
{name: 'type', mapping: 'type'},
{name: 'history', mapping: 'history'},
{name: 'src', mapping: 'url'},
{name: 'search_tag', mapping: 'search_tag'},
{name: 'new_element', mapping: 'new_element'},
{name: 'new_table', mapping: 'new_table'}
],
autoLoad: true,
proxy: {
//type:'ajax',
type:'jsonp',
url: baseUrl + 'openbd/ktimatologio-final/resources/cfScripts/nea_stoixeia/GetNewTables.cfc?',
extraParams: {
method: 'getNewTables'
},
reader:{
type: 'json',
root: 'data'
}
}
When i run the code i see an error on firebug:
SyntaxError: invalid label
{"data":[{"id":"1_n_2308_1995","id1":1,"title":"Άρθρο 1&nbspΦΕΚ Α΄ 114&nbsp15.6....
GetNew...llback2 (line 1, column 1)
I am stuck!
Any help is much appreciated!
Tom
Greece
JSONP service must actually return a function call not just JSON back. Google for some examples.

json to load values into extjs checkboxgroup grid editor

I need to set up a CheckboxGroup checkboxes with values loaded with json from some url.
What is a correct format of JSON?
Many thanks for help!
Update: I'll clarify my problem.
I'm using EditorGridPanel. Rows are Periods. There are columns Start_at, Finish_at, Region. First and second are date and everything ok with them. Problem with Region which actually is a CheckboxGroup with a checkbox for each week day - Monday, Tuesday, etc. So:
First I'm loading data from server into store
function setupDataSource() {
row = Ext.data.Record.create([
{ name: 'start_at', type: 'string' },
{ name: 'finish_at', type: 'string' },
{ name: 'region', type: 'string' }
]);
store = new Ext.data.Store({
url: '/country/195/periods',
reader: new Ext.data.JsonReader(
{
root: 'rows',
id: 'id'
},
row
)
});
store.load();
}
URL url: '/country/195/periods' returns JSON:
{"rows": [{"region": {"cbvert_1": 1, "cbvert_2": 0, "cbvert_3": 1, "cbvert_4": 0, "cbvert_5": 1, "cbvert_6": 0, "cbvert_7": 1}, "start_at": "2010-10-17", "id": 1, "finish_at": "2010-10-28"}]}
Then I'm building a grid:
function buildGrid() {
sm = new Ext.grid.RowSelectionModel();
cm = new Ext.grid.ColumnModel([
// ... Start at and Finish at columns definition here ...
{ header: 'Region',
dataIndex: 'region',
width: 150,
editor: new Ext.form.CheckboxGroup({
xtype: 'checkboxgroup',
columns: 7,
vertical: true,
items: [
{boxLabel: 'M', name: 'cbvert_1', inputValue: 1},
{boxLabel: 'T', name: 'cbvert_2', inputValue: 1},
{boxLabel: 'W', name: 'cbvert_3', inputValue: 1},
{boxLabel: 'T', name: 'cbvert_4', inputValue: 1},
{boxLabel: 'F', name: 'cbvert_5', inputValue: 1},
{boxLabel: 'S', name: 'cbvert_6', inputValue: 1},
{boxLabel: 'S', name: 'cbvert_7', inputValue: 1},
]
}),
renderer: function(value) {}
}]);
// ...
}
So, when I'm clicking on a grid cell I need to get checkboxes preselected with values previously stored in database. Now all checkboxes are stay blank but should be 1010101 as its in JSON.
Please point me to errors or maybe a some kind of a solution. Any help will be greatly appreciated.
Many thanks!
Check this out:
http://www.sencha.com/forum/showthread.php?47243-Load-data-in-checkboxgroup
Updated:
Remove the type declaration of the region field. You do not need a string but an object (from JSON). It works just fine that way :)