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).

Answer from Simon Crowe on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › how to map/convert a number to string
r/learnpython on Reddit: How to map/convert a number to string
September 13, 2021 -

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!

Discussions

java - Converting Map<String, Object> to json - Stack Overflow
If I convert it into a json and get the response from jsp can I able get the appropriate boolean in jsp where the "canApprove" refers an Object in the responseObj? Can I persist the "userId" and "roleId" to JSON from User Class? ... What did you try? As for no.1: I don't know gson but I assume it might just work. Other JSON libs have JSONObject classes that basically are maps ... More on stackoverflow.com
🌐 stackoverflow.com
Serialize a Map into a specific JSON object - Salesforce Stack Exchange
I built a Map and serialized it into a JSON object, my code below: Map 0){ ... More on salesforce.stackexchange.com
🌐 salesforce.stackexchange.com
February 23, 2017
java - Converting Map<String,String> into json - Stack Overflow
Is that possible to convert Map into json? More on stackoverflow.com
🌐 stackoverflow.com
Convert string to JSON in Python? - Stack Overflow
What do you mean "Convert string to JSON"? JSON is a string format. You want to convert JSON to the appropriate native Python objects (in this case a dict mapping one string to another)? More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python Examples
pythonexamples.org › javascript › how-to-convert-a-map-to-a-json-string
How to Convert a Map to a JSON String in JavaScript
However, since `JSON.stringify` does not directly support `Map`, we need to convert the map to an object first.
🌐
iProyal
iproyal.com › blog › python-string-to-json
How to Convert a Python String to JSON (Beginner’s Guide)
August 18, 2025 - JSON object structures are ideal ... To convert a Python object like a Python dictionary into a JSON string, you need to use the json.dumps() method from Python’s JSON module....
🌐
GeeksforGeeks
geeksforgeeks.org › python-convert-dictionary-object-into-string
Python - Convert Dictionary Object into String - GeeksforGeeks
April 11, 2025 - To use this feature, we import the Python JSON package into Pytho ... Python provides built-in type conversion functions to easily transform one data type into another. This article explores the process of converting objects into strings which is a basic aspect of Python programming.Since every element in Python is an object, we can use the built-in str() and repr() m
🌐
Medium
medium.com › @glasshost › how-to-convert-a-map-to-json-in-javascript-b8a6ae3abedd
How to Convert a Map to JSON in JavaScript | by Glasshost | Medium
May 3, 2023 - let myMap = new Map(); myMap.set('key1', 'value1'); myMap.set('key2', 'value2'); myMap.set('key3', 'value3'); let myObj = Object.fromEntries(myMap); let myJSON = JSON.stringify(myObj); console.log(myJSON); // Output: {"key1":"value1","key2"...
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-convert-a-map-to-json-string-in-javascript
How to Convert a Map to JSON String in JavaScript ? - GeeksforGeeks
July 23, 2025 - A Map is a collection of key-value pairs, where each key is unique. In this article, we will see how to convert a Map to a JSON (JavaScript Object Notation) string in JavaScript.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-convert-json-to-string
Convert JSON to string - Python - GeeksforGeeks
July 12, 2025 - print(type(y)) prints the type of the variable y, which will be <class 'str'> since the JSON data is now a string. This code makes a GET request to a dummy API to fetch employee data, converts the JSON response into a Python dictionary using ...
🌐
QA Automation Expert
qaautomation.expert › 2021 › 11 › 22 › serialization-how-to-convert-map-to-json-string-using-jackson-api
Serialization – How to convert Map to JSON string using Jackson API
December 8, 2022 - { "skillset" : [ "Java", "Teradata", "Python", "Power BI" ], "gender" : "female", "DOB" : "12-02-1985", "name" : "Vibha Singh", "contactNumber" : "+919999988822", "employeeId" : "10342256", "location" : "Dublin", "emailId" : "abc@test.com", "salary" : "75000.0" } First, we will populate a Map, then convert them into JSON and later write that JSON to a file. @Test public void SerializationMapTest() { ObjectMapper mapper = new ObjectMapper(); Map<String, Object> inputMap = new HashMap<String, Object>(); inputMap.put("employeeId", "10342256"); inputMap.put("name", "Vibha Singh"); inputMap.put("DO
🌐
FavTutor
favtutor.com › blogs › convert-dict-to-string-python
How to Convert Dictionary to String in Python? (3 Best Methods)
October 12, 2022 - Another method to convert a dictionary into a string in Python is using the dumps() method of the JSON library. The dumps() method takes up a JSON object as an input parameter and returns a JSON string.
Top answer
1 of 4
18

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:

2 of 4
10

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);
🌐
GitHub
github.com › Kotlin › kotlinx.serialization › issues › 746
How to convert map into json string · Issue #746 · Kotlin/kotlinx.serialization
March 9, 2020 - example val params = mutableMapOf () params.put("long", 100L) params.put("int", 10) params.put("string", "haha") params.put("map", mutableMapOf("longg" to 10L, "stringg" to "ok")) LogUtil.d("test", json.stringify(params))
Author: Kotlin
🌐
GitHub
github.com › google › gson › issues › 1080
how should i convert a map to json String with gson · Issue #1080 · google/gson
May 18, 2017 - My code likes: @Test public void testGsonTransferMap(){ HashMap map = new HashMap () {{ put("Request", new HashMap (){{ put("Data",new HashMap (){{ put("NWExID", "7019"); put("O...
🌐
W3Schools
w3schools.com › python › gloss_python_convert_into_JSON.asp
Python Convert From Python to JSON
Remove List Duplicates Reverse ... ... If you have a Python object, you can convert it into a JSON string by using the json.dumps() method....
🌐
PyPI
pypi.org › project › json-converter
json-converter · PyPI
The JsonMapper class is a tool for translating/converting a JSON document into another JSON document with a different structure. The mapping process follows a dictionary-based specification of how fields map to the new JSON format.