The problem was mixing bytes and str values. Ensuring that everything is in bytes makes it work because urandom returns bytes.
# Encode the concatenated strings into a byte string
chars = (string.ascii_letters + string.digits + string.punctuation).encode()
char_gen = (c for c in map(urandom, repeat(1)) if c in chars)
# Use an empty byte string to join the generated bytes
pswd_text = b''.join(islice(char_gen, None, string_len))
You can always call pswd_text.decode() to get a unicode string (str).
Hi,
I am trying to write an Icinga check in Python which checks the status of my Keepalived setup. It has several status codes.
I'd like to convert those status codes to something human readable which makes sense. So I am thinking about a dict, something like: state_codes = {0: "init", 1: "backup", 2: "master", 3: "fault", 4: "goto master", 98: "goto fault"} which contains all the possible codes.
I have a JSON object which has the data:
[{
"data": {
"iname": "VRRP_1",
"state": 1,
"wantstate": 1,
}
}]
So the thing is I want to print something like VRRP_1 has state <STATE> and wants state <WANTSTATE>, in stead of the numbers.
How would one do that?
Thank you!
Try this :
public static class User
{
public User(int userId, int roleId)
{
this.userId = userId;
this.roleId = roleId;
}
private int userId;
private int roleId;
public int getUserId()
{
return userId;
}
public int getRoleId()
{
return roleId;
}
public void setUserId(int userId)
{
this.userId = userId;
}
public void setRoleId(int roleId)
{
this.roleId = roleId;
}
}
Test :
Map<String, Object> responseObj = new HashMap<String, Object>();
List<User> userList = new ArrayList<User>();
userList.add(new User(1, 1));
userList.add(new User(2, 2));
responseObj.put("canApprove", true); //1
responseObj.put("approvers", userList);
System.out.println(new JSONObject(responseObj));
Prints :
{"approvers":[{"userId":1,"roleId":1},{"userId":2,"roleId":2}],"canApprove":true}
(formatted)
You can try to use JSONObject to parse the map to JSON.
The maven dependency is:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
later create a new JSON object and pass the map
JSONObject obj = new JSONObject(responseObj);
and return the object to this web client.
Hi there
A friend and I are working on an economy simulation on randomly generated landscapes. When looking into map generation, I found this amazing project. Aside from the very impressive artwork, there are quite a lot details for each spot on the map (much more than we can use at this stage).
I wrote a little python script (almost entirely based on save-and-load.js) to convert some data from exported .map files to json. For me it's mostly for testing around. The result is very raw data which is also already included in the .map files, but it might help porting the maps to other applications.
You can find it here: https://pastebin.com/V03gDLqe
Run it like this to spawn a json-file in the same folder as your mapfile.map (only tested on linux):
python3 -i fmg_map_to_json.py ~/home/user/mapfile.map
Note that not all data from the map files will be included in the json file. That script might also not work with a different version than 0.9b. But it shouldn't be too complicated to modify it accordingly. If I get to expand on this script, I can notify you.
Thank you Azgaar for this spectacular tool. It is the most accessible (and beautiful) map generator I've seen online.
Here how you can achieve it.
map<string, object> mapToSerialize = new map<string, object>();
mapToSerialize.put('type', 'TEST');
//add you subtype like this
mapToSerialize.put('subtypes', new list<string>{'TEST'});
string jsonstring = JSON.serialize(mapToSerialize);
May be the following sample code helps:
Map<Object,List<Object>> mapTypeSubType= new Map<Object,List<Object>>();
for(Integer i=0; i<3; i++){
if(!mapTypeSubType.containskey('"type":"TEST"')){
mapTypeSubType.put('"type":"TEST"',new List<Object> {'"subtypes":"TEST"'});
}else{
mapTypeSubType.get('"type":"TEST"').add('TEST');
}
}
System.debug(mapTypeSubType);
String jsonMap=JSON.serialize(mapTypeSubType);
System.debug(jsonMap);
//Here's the debug response:
{"\"type\":\"TEST\"":["\"subtypes\":\"TEST\"","TEST","TEST"]}
You can also try something like this with Gson Library:
package com.stackoverflow.works;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/*
* @Author: sarath_sivan
*/
public class MapToJsonConverter {
/*
* @Description: Method to convert Map to JSON String
* @param: map Map<String, String>
* @return: json String
*/
public static String convert(Map<String, String> map) {
Gson gson = new Gson();
String json = gson.toJson(map);
return json;
}
/*
* @Description: Method to convert JSON String to Map
* @param: json String
* @return: map Map<String, String>
*/
public static Map<String, String> revert(String json) {
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = gson.fromJson(json, type);
return map;
}
/*
* @Description: Method to print elements in the Map
* @param: map Map<String, String>
* @return: void
*/
public static void printMap(Map<String, String> map) {
for (String key : map.keySet()) {
System.out.println("map.get(\"" + key + "\") = " + map.get(key));
}
}
/*
* @Description: Method to print the JSON String
* @param: json String
* @return: void
*/
public static void printJson(String json) {
System.out.println("json = " + json);
}
/*
* @Description: Main method to test the JSON-MAP convert/revert logic
*/
public static void main(String[] args) {
Map<String, String> paymentCards = new HashMap<String, String>();
paymentCards.put("card_switch", "Master");
paymentCards.put("issuing_bank", "ICCI");
paymentCards.put("card_Type", "DebitCard");
String json = convert(paymentCards); //converting Map to JSON String
System.out.println("Map to JSON String");
System.out.println("******************");
printJson(json);
System.out.println();
paymentCards = revert(json); //converting JSON String to Map
System.out.println("JSON String to Map");
System.out.println("******************");
printMap(paymentCards);
}
}
The output look like this:

Have a look at example 1.4 on this page http://code.google.com/p/json-simple/wiki/EncodingExamples#Example_1-4_-_Encode_a_JSON_object_-_Using_Map_and_streaming:
Map obj=new LinkedHashMap();
obj.put("name","foo");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
obj.put("nickname",null);
StringWriter out = new StringWriter();
JSONValue.writeJSONString(obj, out);
String jsonText = out.toString();
System.out.print(jsonText);
You need some key=value pair on each line representing one map entry, and you need quotes around the values:
package main
import (
"bytes"
"fmt"
)
func createKeyValuePairs(m map[string]string) string {
b := new(bytes.Buffer)
for key, value := range m {
fmt.Fprintf(b, "%s=\"%s\"\n", key, value)
}
return b.String()
}
func main() {
m := map[string]string{
"LOG_LEVEL": "DEBUG",
"API_KEY": "12345678-1234-1234-1234-1234-123456789abc",
}
println(createKeyValuePairs(m))
}
Here is a working example on Go Playground.
You can use fmt.Sprint to convert the map to string:
import (
"fmt"
)
func main() {
m := map[string]string{
"a": "b",
"c": "d",
}
log.Println("Map: " + fmt.Sprint(m))
}
Or fmt.Sprintf:
import (
"fmt"
)
func main() {
m := map[string]string{
"a": "b",
"c": "d",
}
log.Println(fmt.Sprintf("Map: %v", m))
}
json.dumps() converts a dictionary to str object, not a json(dict) object! So you have to load your str into a dict to use it by using json.loads() method
See json.dumps() as a save method and json.loads() as a retrieve method.
This is the code sample which might help you understand it more:
import json
r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
loaded_r = json.loads(r)
loaded_r['rating'] #Output 3.5
type(r) #Output str
type(loaded_r) #Output dict
json.dumps() returns the JSON string representation of the python dict. See the docs
You can't do r['rating'] because r is a string, not a dict anymore
Perhaps you meant something like
r = {'is_claimed': 'True', 'rating': 3.5}
json = json.dumps(r) # note i gave it a different name
file.write(str(r['rating']))