Json Object Hay Nhất 2022, Convert Array To Json Object Javascript

If you’re working with JSON (JavaScript Object Notation) & either need khổng lồ convert a JSON string to array or object và loop through it or vice-versa, take an array or object and convert it to lớn a JSON string lớn return, both can be done in PHP or JavaScript.Bạn đang xem: How to lớn encode và decode json data in php

I broke up this post into three sections:

Convert JSON String to lớn PHP Array or Object

PHP >= 5.2.0 features a function, json_decode, that decodes a JSON string into a PHP variable. By mặc định it returns an object. The second parameter accepts a boolean that when phối as true, tells it to return the objects as associative arrays. You can learn more about the json_decode function from PHP’s documentation.

Bạn đang xem: Json object hay nhất 2022, convert array to json object javascript

// JSON string $someJSON = ""; // Convert JSON string to lớn Array $someArray = json_decode($someJSON, true); print_r($someArray); // Dump all data of the Array echo $someArray; // Access Array data // Convert JSON string lớn Object $someObject = json_decode($someJSON); print_r($someObject); // Dump all data of the Object echo $someObject->name; // Access Object data?>

Loop through PHP Array or Object

Loop through a PHP array or object with a foreach loop.

// Loop through Array $someArray = ...; // Replace ... With your PHP Array foreach ($someArray as $key => $value) echo $value . ", " . $value . ""; // Loop through Object $someObject = ...; // Replace ... With your PHP Object foreach($someObject as $key => $value) echo $value->name . ", " . $value->gender . ""; ?>Note the differences in accessing the values of an array vs an object.

Convert PHP Array or Object lớn JSON String

PHP also features a json_encode function to lớn convert an array or object into a string. Read more about the json_encode function from PHP’s documentation.

// Array $someArray = "Jonathan Suh", "gender" => "male" >, "William Philbin", "gender" => "male" >, "Allison McKinnery", "gender" => "female" > >; // Convert Array khổng lồ JSON String $someJSON = json_encode($someArray); echo $someJSON;?>Note that I’m using the short array syntax that’s featured in PHP 5.4+.

$array = array( "foo" => "bar", "bar" => "foo" ); // as of PHP 5.4 $array = "bar", "bar" => "foo" >;?>

Convert JSON String to JavaScript Object

JavaScript has a built-in JSON.parse() method that parses a JSON string and returns an object.

script> // Convert JSON String lớn JavaScript Object var JSONString = ""; var JSONObject = JSON.parse(JSONString); console.log(JSONObject); // Dump all data of the Object in the console alert(JSONObject); // Access Object data/script>JSON.parse() is very well-supported, but there are browsers that bởi vì not tư vấn it (i.e. Caniuse.com).

jQuery 1.x has a $.parseJSON() method that should fill in the gaps for those browsers if you’re needing to tư vấn them. You can also use the JSON-js library as a polyfill.

script> // Convert JSON String to JavaScript Object with jQuery var JSONString = "..."; // Replace ... With your JSON String var JSONObject = $.parseJSON(JSONString); console.log(JSONObject); // Dump all data of the Object in the console alert(JSONObject); // Access Object data/script>

Loop through JavaScript Object

script> // Loop through Object var JSONObject = ...; // Replace ... With your JavaScript Object for (var key in JSONObject) if (JSONObject.hasOwnProperty(key)) console.log(JSONObject + ", " + JSONObject); /script>

Convert JavaScript Object lớn JSON String

JavaScript has a JSON.stringify method to convert a value into a JSON string.

Xem thêm: Nấu Nước Gội Đầu Cho Bà Đẻ Gội Đầu Bằng Lá Gì, Phụ Nữ Sau Sinh Gội Đầu Bằng Gì

script> var JSONObject = ; var JSONString = JSON.stringify(JSONObject); alert(JSONString);/script>Like JSON.parse, JSON.stringify is not supported in dinosaur browsers like JSON-js library khổng lồ polyfill JSON.stringify as well.

You can combine the methods above to lớn create powerful, dynamic implementations on your website or application.

Let’s say you want to lớn get information from a database, safely return the data as JSON, & loop through it dynamically, you can do so with a bit of PHP & JavaScript with Ajax.

Dynamically Get JSON via Ajax và Loop Through JSON

Let’s assume your database structure looks lượt thích the following:

Table: people┌────┬────────────────────┬─────────┐| id | name | gender |├────┼────────────────────┼─────────┤| 0 | Jonathan Suh | male || 1 | William Philbin | male || 2 | Allison McKinnery | female || 3 | Becky Borgster | female || 4 | Victoria Einsteen | female |└────┴────────────────────┴─────────┘And you want to lớn dynamically get a danh sách of people from the database based on gender, lượt thích this:


Let’s start with the front-end tệp tin index.html that’ll have a select dropdown with genders to lớn select from, a table lớn display the results, and the script khổng lồ handle the Ajax. The JavaScript is written in jQuery.

id="gender" name="gender"> value="male">Male value="female">Female

id="people" border="1"> Name Gender
Now let’s create a response.php tệp tin to handle the back-end xúc tích of getting the information from the database và returning the results as a JSON string.

// File: response.php // Get POST gender value $gender = $_POST; // Connect lớn the database // replace the parameters with your proper credentials $connection = mysqli_connect("localhost", "username", "password", "database_name"); // Query lớn run $query = mysqli_query($connection, "SELECT * FROM people WHERE gender = "" . $gender . """); // Create empty array to lớn hold query results $someArray = ; // Loop through query & push results into $someArray; while ($row = mysqli_fetch_assoc($query)) array_push($someArray, $row, "gender" => $row >); // Convert the Array khổng lồ a JSON String và echo it $someJSON = json_encode($someArray); echo $someJSON;?>To get a more in-depth & better example of PHP-JSON-JavaScript/jQuery-Ajax interaction, read my jQuery Ajax điện thoại tư vấn to PHP Script with JSON Return post.

nội dung ← Previous Post Next Post →

Related posts


Jonathan Suh

I’m a multidisciplinary developer & designer. I’m currently with the folks at Planning Center, & I’ve worked with well-known brands & agencies, which include Allstate, Brian Hoff Design, Leo Burnett, và OLSON. More about me. Follow obatambeienwasirherbal.com.com

Selected posts Post Topics Say hey! Subscribe

Stay up-to-date with all the blog posts via RSS or the Archives.

You can also subscribe lớn my newsletter lớn receive occasional emails from me.