def toNumber(json): if isinstance(json, list): return sum([toNumber(x) for x in json]) elif isinstance(json, dict): return 0 if 'red' in json.values() else sum([toNumber(x) for x in json.values()]) elif isinstance(json, str): return 0 else: return json
def getnumbers(json): if type(json) == type(0): return json if type(json) == type([]): return sum(map(getnumbers, json)) if type(json) == type({}) and not 'red' in json.values(): return sum(map(getnumbers, json.values())) return 0
def sumNumbers(json, skipped=None): if isinstance(json, int): return json elif isinstance(json, dict): return 0 if skipped in json.values() else sumNumbers( list(json.values()), skipped) elif isinstance(json, list): return sum(map(sumNumbers, json, len(json) * [skipped])) else: return 0
def find_target(json, target, targets): if isinstance(json, dict): if target not in json.values(): for item in json.values(): find_target(item, target, targets) else: targets.append(json) if isinstance(json, list): for item in json: find_target(item, target, targets)
def sum_json(json, ignore_red=False): if isinstance(json, int): return json elif isinstance(json, list): return sum(sum_json(j, ignore_red=ignore_red) for j in json) elif isinstance(json, dict): if 'red' in json.values() and ignore_red: return 0 else: return sum(sum_json(j, ignore_red=ignore_red) for j in json.values()) elif isinstance(json, str): return 0 raise NotImplementedError(type(json))
def sum_json_no_red(json): if isinstance(json, int): return json if isinstance(json, list): return sum(sum_json_no_red(item) for item in json) if isinstance(json, dict): if 'red' in json.values(): return 0 return sum(sum_json_no_red(item) for item in json.values()) return 0
def sum_all(json): if isinstance(json, int): return json elif isinstance(json, str) or isinstance(json, unicode): return 0 elif isinstance(json, list) or isinstance(json, tuple): return sum(sum_all(x) for x in json) elif isinstance(json, dict): if (part == 2): if 'red' in json.values(): return 0 else: return sum_all(json.values()) return sum_all(json.values())
def update(self): try: json = self.request.json except ValueError: json = None file_ = self.request.params.get('file') if self.form_submit() and file_ is None: self.result = { 'status': 'error', 'msg': 'Ein unerwarteter Fehler ist aufgetreten' } elif file_ is not None: created, route_name = self.handle_upload(file_) transaction.savepoint() result = self.resource_data_item(created, route_name) log_with_user(user_data_log.info, self.request.user, 'Datei in %s %s hochgeladen.', self.title.split(' ')[0], self.context.id) elif json and list(json.keys())[0] != 'attachments': error = self.save(list(json.keys())[0], list(json.values())[0]) if error: result = {'status': 'error', 'msg': error} else: log_with_user(user_data_log.info, self.request.user, '%s %s bearbeitet.', self.title.split(' ')[0], self.context.id) result = {'status': 'success'} else: if not self.context.id: transaction.savepoint() result = self.get_result() self.result = result
def get_values_by_key(self,key,json): result=[] # 保存找的value值 # value='' # 1.判断json的类型 if isinstance(json,dict): # 2. 如果是字典 if key in json.keys(): # (1)判断key是否在字典的keys里面,在则直接取值,添加到result中 result.append(json.get(key)) #(2)如果不在keys里,则在字典的values中继续查找(遍历values) else: for value in json.values(): print(value) result += (self.get_values_by_key(key,value)) # 3. 如果是列表 elif isinstance(json,list): # 3.1 遍历列表 for j in json: # 3.2 判断是否存在于每个字典对象中,在字典对象中继续查找key result += (self.get_values_by_key(key,j)) # 4. 都不是,直接返回 else: return [] return result
def profundidad(json): result = 0 if isinstance(json, dict): result += 1 + (max(map(profundidad, json.values()) if json else 0)) if isinstance(json, list): result += 1 + (max(map(profundidad, json) if json else 0)) return result
def assign_groups(request): json = request.data if request.method == 'POST': username = json.keys()[0] data = json.values()[0] for entry in data: user = User.objects.get(username=username) time = entry['time'].split(':')[0] + ':' + entry['time'].split(':')[1] timestamp = datetime.combine( datetime.strptime(entry['date'], '%d/%m/%Y').date(), datetime.strptime(time, '%H:%M').time() ) GroupLocalization.objects.create( user=UserProfile.objects.get(user=user), timestamp=timestamp, group=str(entry['group']) ) location = assign_geofence(entry['location']['lat'], entry['location']['long']) if LocationDensity.objects.filter(timestamp=timestamp, location=location).exists(): loc_obj = LocationDensity.objects.get(timestamp=timestamp, location=location) loc_obj.density += 1 loc_obj.save() else: LocationDensity.objects.create(timestamp=timestamp, location=location, density=1) return Response({"message": "Got some data!", "data": request.data}) return Response({"message": "Data format inaccurate !!!!!"})
def jsonTo164Object(json): """Convert the JSON string "json" into a 164 object.""" # Essentially need to convert the python list into a 164 list # 164 lists are dictionaries indexed by ints from 0 and onward # so we just need to iterate through the python list and turn it # a dictionary with that sort of key/value and that's our 164 list retList = {} counter = 0 # this if only works for youtube.... if (type(json) == dict): for element in json.values(): if (type(element) == dict): for e in element.values(): if (type(e) == list): for e2 in e: retList[counter] = e2 counter = counter + 1 else: for element in json: retList[counter] = element counter = counter + 1 #print retList return retList
def format_graph(self, json): links, nodes, dictN = [], [], {} for src in json: psrc = self.prepareName(src) for tar in json[src]: tar = self.prepareName(tar) # build links links.append({'source': psrc, 'target': tar}) # calculate node with degree if psrc in dictN: dictN[psrc] += 1 else: dictN[psrc] = 2 # ensure target nodes exist in nodes for ns in json.values(): for n in ns: node = self.prepareName(n) if not node in dictN: dictN[node] = 2 # build nodes for n in dictN: if dictN[n] > 0: deg = math.log(dictN[n]) nodes.append({'id': n, 'degree': deg}) return ({'nodes': nodes, 'links': links})
def print_json(self, json): for item in sorted(json.values(), key=lambda item: item['sort_id']): if self.direct: msg = "{}: {}" print(msg.format(item['resolved_title'], item['given_url'])) else: msg = "{}: https://getpocket.com/a/read/{}" print(msg.format(item['resolved_title'], item['item_id']))
def as_json(self, keys: Iterable[str]) -> JSON: keys = set(keys) if keys: require(keys.issubset(self.all_keys())) else: keys = self.all_keys() json = {k: getattr(self, k) for k in keys} json['up'] = all(v['up'] for v in json.values()) return json
def sum_numbers_in_json(json): if isinstance(json, int): return json elif isinstance(json, list): return sum(sum_numbers_in_json(x) for x in json) elif isinstance(json, dict): return sum(sum_numbers_in_json(x) for x in json.values()) return 0
def search_json(matches, match_fn, json): if match_fn(json): matches.append(json) elif isinstance(json, list): for item in json: search_json(matches, match_fn, item) elif isinstance(json, dict): for val in json.values(): search_json(matches, match_fn, val) return matches
def __valid_fields(self, json): for value in json.values(): if type(value) is dict: return self.__valid_fields(value) if value[0].upper() != 'REQUIRED' and value.upper() != 'OPTIONAL': return False if value[1].upper() != 'STRING' and value[1].upper() != 'NUMBER': return False return True
def get_stream_from_url(self, url): cred = helperobjects.Credentials(self._addon) if not cred.are_filled_in(): self._addon.openSettings() cred.reload() url = urlparse.urljoin(self._vrt_base, url) r = self._session.post( "https://accounts.eu1.gigya.com/accounts.login", { 'loginID': cred.username, 'password': cred.password, 'APIKey': self._API_KEY, 'targetEnv': 'jssdk', 'includeSSOToken': 'true', 'authMode': 'cookie' }) logon_json = r.json() if logon_json['errorCode'] == 0: uid = logon_json['UID'] sig = logon_json['UIDSignature'] ts = logon_json['signatureTimestamp'] headers = { 'Content-Type': 'application/json', 'Referer': self._vrtnu_base_url } data = '{"uid": "%s", ' \ '"uidsig": "%s", ' \ '"ts": "%s", ' \ '"email": "%s"}' % (uid, sig, ts, cred.username) response = self._session.post("https://token.vrt.be", data=data, headers=headers) securevideo_url = "{0}.securevideo.json".format( self.__cut_slash_if_present(url)) securevideo_response = self._session.get(securevideo_url, cookies=response.cookies) json = securevideo_response.json() mzid = list(json.values())[0]['mzid'] final_url = urlparse.urljoin(self._BASE_GET_STREAM_URL_PATH, mzid) stream_response = self._session.get(final_url) hls = self.__get_hls(stream_response.json()['targetUrls']).replace( "https", "http") subtitle = None if self._addon.getSetting("showsubtitles") == "true": subtitle = self.__get_subtitle( stream_response.json()['subtitleUrls']) return helperobjects.StreamURLS(hls, subtitle) else: xbmcgui.Dialog().ok(self._addon.getAddonInfo('name'), self._addon.getLocalizedString(32051), self._addon.getLocalizedString(32052))
def recurse(json): if isinstance(json, list): return _flatten_list(map(recurse, json)) elif isinstance(json, dict): ret = [] if field in json: ret = [json[field]] del json[field] ret += _flatten_list(map(recurse, json.values())) return ret return []
def export(ws, json): headers = [] list_headers(list(json.values())[0], headers) for i, label in enumerate(headers): ws.cell(row=2 + i, column=1, value=label) for i, player in enumerate(json): ws.cell(row=1, column=2 + i, value=player) for j, val in enumerate(dump_values(json[player])): ws.cell(row=2 + j, column=2 + i, value=val)
def cluster_slots() -> Dict[str, Any]: """ cluster_slots returns a dict of slots that each agent has. :return: Dict[AgentID, List[Slot]] """ # TODO: refactor tests to not use cli singleton auth. certs.cli_cert = certs.default_load(conf.make_master_url()) authentication.cli_auth = authentication.Authentication(conf.make_master_url(), try_reauth=True) r = api.get(conf.make_master_url(), "agents") assert r.status_code == requests.codes.ok, r.text json = r.json() # type: Dict[str, Any] return {agent["id"]: agent["slots"].values() for agent in json.values()}
def sum_json(json): if isinstance(json, int): return json if isinstance(json, list): return sum(sum_json(item) for item in json) if isinstance(json, dict): return sum(sum_json(item) for item in json.values()) return 0
def print_json(self, json): for item in sorted(json.values(), key=lambda item: item['sort_id']): try: title = item['resolved_title'] except KeyError: title = '<no title found>' if self.direct: msg = "{}: {}" print(msg.format(title, item['given_url'])) else: msg = "{}: https://getpocket.com/a/read/{}" print(msg.format(title, item['item_id']))
def print_json(self, json): for item in sorted(json.values(), key=lambda item: item['sort_id']): try: title = item['resolved_title'] except KeyError: title = '<no title found>' if self.direct: msg = "{}: {}" print(msg.format(title, item['given_url'])) else: msg = "{}: https://app.getpocket.com/read/{}" print(msg.format(title, item['item_id']))
def list_result(self, json, clazz=None): date = datetime.datetime.utcnow() output = [] for raw in json.values(): if self.include_timestamp: raw['date'] = date mplist = clazz(json=raw) output.append(mplist) return output
def get(self, method='mobiledevices'): try: self.r = requests.get(url=(self.url + method), headers=self.head, auth=self.auth) if self.r.status_code != 200: self.r.raise_for_status() # Convert to JSON json = self.r.json() return next(iter(json.values())) except: self.e = sys.exec_info[0] return []
def _simplify_json(self, json): result = {} # First, resolve references for element in json.values(): for k,v in element.items(): if isinstance(v, unicode) and v.startswith("http://") and json.has_key(v): element[k] = json[v] for k, v in json.items(): if v.has_key("_typeGroup"): group = v["_typeGroup"] if not result.has_key(group): result[group]=[] del v["_typeGroup"] v["__reference"] = k result[group].append(v) return result
def _parseJSONForSum(self, json): """ Returns a dictionary of {'total_hits': x, 'unique_hits': y} for the date range. """ totalHits = {self._strTotalHits: 0, self._strUniqueHits: 0} # Piwik has an odd format of returning this data, dictionaries inside # a list of days, reduce it so that we can easily sum. dayDicts = list(d[0] for d in json.values() if d) for hits in dayDicts: totalHits[self._strTotalHits] += hits[self._totalHitMetric] totalHits[self._strUniqueHits] += hits[self._totalUniqueHits] return totalHits
def _simplify_json(json): result = {} # First, resolve references for element in json.values(): for k, v in element.items(): if isinstance(v, str) and v.startswith("http://") and v in json: element[k] = json[v] for k, v in json.items(): if "_typeGroup" in v: group = v["_typeGroup"] if not group in result: result[group] = [] del v["_typeGroup"] v["__reference"] = k result[group].append(v) return result
def GetDomainDepsFromRefs(domain_name, json): if isinstance(json, list): for value in json: GetDomainDepsFromRefs(domain_name, value) return if not isinstance(json, dict): return for value in json.values(): GetDomainDepsFromRefs(domain_name, value) if '$ref' in json: if '.' in json['$ref']: dep = json['$ref'].split('.')[0] direct_deps[domain_name].add(dep) types_required[domain_name].add(json['$ref'])
def getvalues_from_json(json,relist,key): #是字典 v='' if isinstance(json,dict): if key in json.keys(): #第一层的jsonkey是否有目标key v=json.get(key) #两种取法 # v=json[key] else: for k in json.values(): getvalues_from_json(k,relist,key) elif isinstance(json, list): for l in json: getvalues_from_json(l,relist,key) if v: relist.append(v) return relist #就像类似递归的,不结束会一直调用
def json_csv(self, tablename, json): """把获取的json数据输出到csv文件 Args: tablename (string): 用于文件民 json (dict/list): 需要输出到csv的数据 Returns: boolean: 返回成功 """ url_cut = urlparse(self.url) with open('./{}/{}.csv'.format(url_cut.netloc, tablename), 'a') as csvfile: writer = csv.writer(csvfile) if type(json) == list: writer.writerow(json) # 在输出列标题的时候,传入的是list if type(json) == dict: writer.writerow(json.values()) # 输出数据的时候是dict格式 return True
def get_available_monomers(request): reason = None if request.method == 'POST' and "monomer[]" in request.POST: monomers = request.POST.getlist("monomer[]") if 'selected' in request.POST: selected = int(request.POST['selected']) else: selected = None aas, reason = get_available_substrates(monomers, toBool(request.POST['current']), toBool(request.POST['curatedonly']), selected) else: aas = filter(lambda x: x.can_be_added(curatedonly=toBool(request.POST['curatedonly'])), Substrate.objects.exclude(user__username='******')) reason = 0 json = {} minid = float("Inf") for aa in aas: if aa.parent is None: name = aa.name if aa.name[0:2].upper() == 'L-' or aa.name[0:2].upper() == 'D-': name = aa.name[2:] if aa.pk in json: key = aa.pk elif aa.enantiomer is not None and aa.enantiomer.pk in json: key = aa.enantiomer.pk else: key = None if aa.enantiomer is None: chirality = 'N' else: chirality = aa.chirality if key is not None: if key < minid: minid = key json[key][chirality.lower() + "id"] = aa.pk json[key][chirality+'Children'] = [{"text": c.name, "id": c.pk} for c in aa.child.all()] #names[name]['name'] = name else: json[aa.pk] = {"id": aa.pk, chirality.lower() + "id": aa.pk, 'text': name, aa.chirality+'Children': [{"text": c.name, "id": c.pk} for c in aa.child.all()]} jsonlist = json.values() jsonlist.sort(lambda x,y: cmp(x['text'], y['text'])) return JsonResponse({"monomers": json, "monomerslist": jsonlist, "reason": reason})
def update_data(): json = request.get_json() values = list(json.values()) key = values[0] val = values[1] n = 0 x = None status = 200 result = True if key in red: red.set(key, val) n += 1 else: x = True status = 404 result = False return jsonify(kv_key=key, kv_value=val, command=('UPDATE ' + key), result=result, error=x), status
def get_available_monomers(request): if request.method == 'POST' and "monomer[]" in request.POST: monomers = request.POST.getlist("monomer[]") if 'selected' in request.POST: selected = int(request.POST['selected']) else: selected = None aas = get_available_substrates(monomers, toBool(request.POST['current']), toBool(request.POST['curatedonly']), selected) else: aas = filter(lambda x: x.can_be_added(), Substrate.objects.exclude(user__username='******')) json = {} minid = float("Inf") for aa in aas: if aa.parent is None: name = aa.name if aa.name[0:2].upper() == 'L-' or aa.name[0:2].upper() == 'D-': name = aa.name[2:] if aa.pk in json: key = aa.pk elif aa.enantiomer is not None and aa.enantiomer.pk in json: key = aa.enantiomer.pk else: key = None if aa.enantiomer is None: chirality = 'N' else: chirality = aa.chirality if key is not None: if key < minid: minid = key json[key][chirality.lower() + "id"] = aa.pk json[key][chirality+'Children'] = [{"text": c.name, "id": c.pk} for c in aa.child.all()] #names[name]['name'] = name else: json[aa.pk] = {"id": aa.pk, chirality.lower() + "id": aa.pk, 'text': name, aa.chirality+'Children': [{"text": c.name, "id": c.pk} for c in aa.child.all()]} jsonlist = json.values() jsonlist.sort(lambda x,y: cmp(x['text'], y['text'])) return JsonResponse({"monomers": json, "monomerslist": jsonlist})
def export(ws, json): font_bold = Font(bold=True) font_italic = Font(italic=True) align_center = Alignment(horizontal='center') align_right = Alignment(horizontal='right') border_bottom = Border( bottom=Side(border_style=BORDER_THIN, color='FF000000')) ws.cell(row=1, column=1, value='name').font = font_bold headers = [[], [], []] list_headers(list(json.values())[0], headers) for i in range(0, len(headers[0])): c = ws.cell(row=1, column=i + 2, value=headers[0][i]) c.font = font_bold c.alignment = align_center for i in range(0, len(headers[1])): c = ws.cell(row=2, column=i + 2, value=headers[1][i]) c.alignment = align_center for i in range(0, len(headers[2])): c = ws.cell(row=3, column=i + 2, value=headers[2][i]) c.font = font_italic c.alignment = align_center for i in range(1, len(headers[0]) + 2): ws.cell(row=3, column=i).border = border_bottom for i, player in enumerate(json): c = ws.cell(row=i + 4, column=1, value=player) c.font = font_bold c.alignment = align_right col = 2 for val in dump_values(json[player]): if val is not None: d = ws.cell(row=i + 4, column=col, value=val) d.alignment = align_center col += 1
def get_values_by_key(self,key, json): result = [] # 保存找到的所有value值 # 1.判断json的类型 if isinstance(json, dict): # 2.如果是字典 # 2.1 判断key是否在字典的keys里面 if key in json.keys(): # 2.1.1 在 value=value 添加到result中 result.append(json.get(key)) else: # 2.1.2 不在 在字典的values中继续查找(遍历values) for value in json.values(): result += self.get_values_by_key(key, value) # 3. 如果是列表 elif isinstance(json, list): # 3.1 遍历列表 for j in json: # 3.2 在每个字典对象中继续查找key result += (self.get_values_by_key(key, j)) else: return [] # 4.都不是,直接返回 return result
def add_data(): json = request.get_json() values = list(json.values()) key = values[0] val = values[1] n = 0 x = '' status = 200 result = True if key in red: n += 1 x = True status = 409 result = False else: red.set(key, val) n += 1 status = 200 return jsonify(kv_key=key, kv_value=val, command=('CREATE ' + key), result=result, error=x), status
import json with open('step1.json') as data_file: json = json.load(data_file) json_ok = [person for person in json.values() if person["condition"] == "OK"] print(len(json_ok))