JSON is the best format to transfer data over network. It is an easily parsable format comparatively. That’s why most of the API accepts parameters and returns responses in JSON.
There are online tools to convert an array to a JSON object. This tutorial teaches how to create a program to convert various types of PHP array input into a JSON format.
It has 4 different examples for converting a PHP array to JSON. Those are too tiny in purpose to let beginners understand this concept easily.
Quick example
This quick example is simply coded with a three-line straightforward solution. It takes a single-dimensional PHP array and converts it to JSON.
The other different array-to-JSON examples handle simple to complex array conversion. It also applies pre-modification (like array mapping) before conversion. The four examples are,
Simple to complex PHP array to JSON.
Remove array keys before converting to JSON.
Convert PHP array with accented characters to JSON
<?php
// PHP Array to JSON string conversion for
// simple, associative and multidimensional arrays
// all works the same way using json_encode
// just present different arrays for example purposes only // simple PHP Array to JSON string
echo '<h1>PHP Array to JSON</h1>';
$array = array( 100, 250, 375, 400
);
$jsonString = json_encode($array);
echo $jsonString; // Associative Array to JSON
echo '<h2>Associative PHP Array to JSON</h2>';
$array = array( 'e1' => 1000, 'e2' => 1500, 'e3' => 2000, 'e4' => 2350, 'e5' => 3000
);
$jsonString = json_encode($array);
echo $jsonString; // multidimensional PHP Array to JSON string
echo '<h2>Multidimensional PHP Array to JSON</h2>';
$multiArray = array( 'a1' => array( 'item_id' => 1, 'name' => 'Lion', 'type' => 'Wild', 'location' => 'Zoo' ), 'a2' => array( 'item_id' => 2, 'name' => 'Cat', 'type' => 'Domestic', 'location' => 'Home' )
);
echo json_encode($multiArray);
?>
Output:
//PHP Array to JSON
[100,250,375,400] //Associative PHP Array to JSON
{"e1":1000,"e2":1500,"e3":2000,"e4":2350,"e5":3000} //Multidimensional PHP Array to JSON
{"a1":{"item_id":1,"name":"Lion","type":"Wild","location":"Zoo"},"a2":{"item_id":2,"name":"Cat","type":"Domestic","location":"Home"}}
2) Remove array keys before converting to JSON
This code handles a different scenario of JSON conversion which must be helpful if needed. For example, if the array associates subject=>marks and the user needs only the marks to plot it in a graph.
It removes the user-defined keys from an associative array and applies json_encode to convert it. It is a two-step process.
It applies PHP array_values() to read the value array.
Then, it applies json_encode on the values array.
<?php
// array_values() to remove assigned keys and convert to the original PHP Array key
echo '<h1>To remove assigned associative keys and PHP Array to JSON</h1>';
$array = array( 'e1' => 1000, 'e2' => 1500, 'e3' => 2000, 'e4' => 2350, 'e5' => 3000
); $jsonString = json_encode(array_values($array));
echo $jsonString;
?>
Output:
[1000,1500,2000,2350,3000]
3) Convert the PHP array with accented characters to JSON
It is also a two-step process to convert the array of data containing accented characters.
It applies UTF8 encoding on the array values before converting them into a JSON object.
For encoding all the elements of the given array, it maps the utf8_encode() as a callback using the PHP array_map() function.
We have seen PHP array functions that are frequently used while working with arrays.
<?php
// Accented characters
// to preserve accented characters during PHP Array to JSON conversion
// you need to utf8 encode the values and then do json_encode
echo '<h1>For accented characters PHP Array to JSON</h1>';
$array = array( 'w1' => 'résumé', 'w2' => 'château', 'w3' => 'façade', 'w4' => 'déjà vu', 'w5' => 'São Paulo'
);
$utfEncodedArray = array_map("utf8_encode", $array);
echo json_encode($utfEncodedArray);
?>
It applies to prettyprint on the converted output JSON properties in a neet spacious format.
The PHP json_encode() function accepts the second parameter to set the bitmask flag. This flag is used to set the JSON_PRETTY_PRINT to align the output JSON properties.
<?php
// to neatly align the output with spaces
// it may be useful when you plan to print the
// JSON output in a raw format
// helpful when debugging complex multidimensional PHP Arrays and JSON objects
// lot more constants are available like this, which might be handy in situations
echo '<h1>Convert PHP Array to JSON and Pretty Print</h1>';
$array = array( 'e1' => 1000, 'e2' => 1500, 'e3' => 2000, 'e4' => 2350, 'e5' => 3000
);
echo json_encode($array, JSON_PRETTY_PRINT);
?>
[www.indiegala.com] A new day, a new opportunity to explore the vast anime universe through videogames with a fresh new selection of titles: Project Heartbeat, Skautfold: Usurper, Jester / King, Neko Journey, My Inner Darkness Is A Hot Anime Girl!, Twilight Town: A Cyberpunk Day In Life.
Posted by: xSicKxBot - 10-23-2022, 01:45 AM - Forum: Lounge
- No Replies
Kerbal Space Program 2 Blasts Off Into Early Access February 2023
Kerbal Space Program 2 is finally releasing into early access February 24 next year, after experiencing numerous delays.
The sequel to the 2015 space flight simulator was meant to launch in early 2021, but was delayed, then delayed again to 2022, and finally a third time to 2023. But a specific date is now locked in, with players able to dig into the game on PC via Steam or the Epic Games Store early next year.
Developer Intercept Games released a 14-minute-long video going into some more detail about the game, announcing the early access release, and explaining why it's decided to take this route. "I cannot overstate how important it is for me to hear what people think about this thing we're creating," explained creative director Nate Simpson. "We've been working in a vacuum for quite a while, this is a rare opportunity to actually find out how we've been doing."
The Last Oricru is a story-driven action RPG, that puts you in the middle of an ongoing conflict between two races, on a partly terraformed planet, isolated from outer space by a protective barrier. Your decisions will bring interesting twists into the gameplay, as you can heavily influence the conflict and its outcome. You will experience hundreds of intense fights in a brutal medieval meets sci-fi world, where every decision has its consequences.
Level up your hero, improve your skills before facing one of many boss fights and get ready for an unprecedented amount of possibilities.
Posted by: xSicKxBot - 10-22-2022, 02:35 AM - Forum: Python
- No Replies
Python | Split String into Characters
Rate this post
Summary: Use the list("given string") to extract each character of the given string and store them as individual items in a list. Minimal Example: print(list("abc"))
Problem: Given a string; How will you split the string into a list of characters?
Example: Let’s visualize the problem with the help of an example:
Approach: One of the simplest ways to solve the given problem is to use the list constructor and pass the given string into it as the input.
list() creates a new list object that contains items obtained by iterating over the input iterable. Since a string is an iterable formed by combining a group of characters, hence, iterating over it using the list constructor yields a single character at each iteration which represents individual items in the newly formed list.
Another way to split the given string into characters would be to use a list comprehension such that the list comprehension returns a new list containing each character of the given string as individual items.
Code:
text = "finxter"
print([x for x in text]) # ['f', 'i', 'n', 'x', 't', 'e', 'r']
Prerequisite: To understand what happened in the above code, it is essential to know what a list comprehension does. In simple words, a list comprehension in Python is a compact way of creating lists. The simple formula is [expression + context], where the “expression” determines what to do with each list element. And the “context” determines what elements to select. The context can consist of an arbitrary number of for and if statements. To learn more about list comprehensions, head on to this detailed guide on list comprehensions.
Explanation: Well! Now that you know what list comprehensions are, let’s try to understand what the above code does. In our solution, the context variable x is used to extract each character from the given string by iterating across each character of the string one by one with the help of a for loop. This context variable x also happens to be the expression of our list comprehension as it stores the individual characters of the given string as separate items in the newly formed list.
Multi-line Solution: Another approach to formulating the above solution is to use a for loop. The idea is pretty similar; however, we will not be using a list comprehension in this case. Instead, we will use a for loop to iterate across individual characters of the given string and store them one by one in a new list with the help of the append method.
text = "finxter"
res = []
for i in text: res.append(i)
print(res) # ['f', 'i', 'n', 'x', 't', 'e', 'r']
Yet another way of solving the given problem is to use a lambda function within the map function. Now, this is complex and certainly not the best fit solution to the given problem. However, it may (or may not ;P) be appropriate when you are handling really complex tasks. So, here’s how to use the two built-in Python functions to solve the given problem:
import re
text = "finxter"
print(list(map(lambda c: c, text))) # ['f', 'i', 'n', 'x', 't', 'e', 'r']
Explanation: The map() function is used to execute a specified function for each item of an iterable. In this case, the iterable is the given string and each character of the string represents an individual item within it. Now, all we need to do is to create a lambda function that simply returns the character passed to it as the input. That’s it! However, the map method will return a map object, so you must convert it to a list using the list() function. Silly! Isn’t it? Nevertheless, it works!
Conclusion
Hurrah! We have successfully solved the given problem using as many as three different ways. I hope you enjoyed this article and it helps you in your Python coding journey. Please subscribe and stay tuned for more interesting articles!
Your grandfather, a genius inventor, has called you for help! His beloved amusement park is about to close as the mayor is threatening to shut everything down and seize the land if the necessary repairs aren't made to bring it up to code. With the help of your powerful little robot buddy, you can restore it using a mysterious device based on alien technology.
As a source of power, the device needs happiness crystals, which you can harvest by making people happy and solving their problems. With the aid of a portal, travel to different locations all around the world to help people and collect their happiness crystals.
Strap in for the ultimate building adventure and save your grandfather's amusement park!
In this puzzle-adventure, use an intuitive brick-by-brick building mechanic to solve puzzles and bring your creations to life! Experience a charming story as you explore beautiful LEGO dioramas and help the people inhabiting them.
Posted by: xSicKxBot - 10-22-2022, 02:35 AM - Forum: Lounge
- No Replies
The Best Metal Gear Games, Ranked
Few video game franchises have been as revolutionary as Metal Gear over the decades, a series that has consistently reinvented itself to offer fresh and exciting twists on tactical espionage action. From the original game that prioritized stealth in an era where action games ruled supreme, to the groundbreaking rebirth of the series that paved the way for cinematic video games, the brainchild of Hideo Kojima has never been short on surprises.
35 years later, the Metal Gear series is a legendary showcase of creative design, intense showdowns, and storylines that helped prove that video games could be cinematic powerhouses. Grab your favorite cardboard box, sneak in for a covert op, and grab some intel on the best Metal Gear Solid games to make the cut in GameSpot's list. Our list is organized from worst to best. We excluded a couple of mobile games and the non-canon Snake's Revenge, but almost the entire franchise is represented here.
The GraalVM 22.3 release delivers several new features including much anticipated support for Java 19 along with preview support for Project Loom virtual threads in both JVM JIT and Native Image ahead-of-time compiled applications. The release also includes compiler performance improvements, new monitoring and debugging features in Native Image, Python enhancements, and a new name for GraalPython!
Posted by: xSicKxBot - 10-21-2022, 09:47 AM - Forum: Python
- No Replies
How to Return a File From a Function in Python?
5/5 – (1 vote)
Do you need to create a function that returns a file but you don’t know how? No worries, in sixty seconds, you’ll know! Go!
A Python function can return any object such as a file object. To return a file, first open the file object within the function body, handle all possible errors if the file doesn’t exist, and return it to the caller of the function using the keyword operation return open(filename, mode='r').
Here’s a minimal example that tries to open a filename that was provided by the user via the input() function. If it fails, it prints an error message and asks for a different user input:
def open_file(): while True: filename = input('filename: ') try: return open(filename, mode='r') except: print('Error. Try again') f = open_file()
print(f.read())
If I type in the correct file right away, I get the following output when storing the previous code snippet in a file named code.py—the code reads itself (meta ):
Note that you can open the file in writing mode rather than reading mode by replacing the line with the return statement with the following line:
open(filename, mode='w')
A more Pythonic way, in my opinion, is to follow the single-responsibility pattern whereby a function should do only one thing. In that case, provide the relevant input values into the function like so:
def open_file(filename, mode): try: return open(filename, mode=mode) except: return None def ask_user(): f = open_file(input('filename: '), input('mode: ')) while not f: f = open_file(input('filename: '), input('mode: ')) return f f = ask_user() print(f.read())
Notice how the file handling of a single instance and the user input processing are separated into two functions. Each function does one thing only. Unix style.
If you want to improve your programming skills and coding productivity creating massive success with your apps and coding projects, feel free to check out my book on the topic:
The Art of Clean Code
Most software developers waste thousands of hours working with overly complex code. The eight core principles in The Art of Clean Coding will teach you how to write clear, maintainable code without compromising functionality. The book’s guiding principle is simplicity: reduce and simplify, then reinvest energy in the important parts to save you countless hours and ease the often onerous task of code maintenance.
Concentrate on the important stuff with the 80/20 principle — focus on the 20% of your code that matters most
Avoid coding in isolation: create a minimum viable product to get early feedback
Write code cleanly and simply to eliminate clutter
Avoid premature optimization that risks over-complicating code
Balance your goals, capacity, and feedback to achieve the productive state of Flow
Apply the Do One Thing Well philosophy to vastly improve functionality
Design efficient user interfaces with the Less is More principle
Tie your new skills together into one unifying principle: Focus
The Python-based The Art of Clean Coding is suitable for programmers at any level, with ideas presented in a language-agnostic manner.
Q: How do you tell an introverted computer scientist from an extroverted computer scientist? A: An extroverted computer scientist looks at your shoes when he talks to you.