CONCAT() का उपयोग करके JSON-जैसा स्ट्रिंग बनाना
JSON फॉर्मेट में रिकॉर्ड प्रदर्शित करने के लिए MySQL CONCAT() का उपयोग करें। पहले टेबल बनाएं:
mysql> create table DemoTable1373 ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentDetails text ); Query OK, 0 rows affected (0.86 sec)
रिकॉर्ड डालें (यहां कुछ नहीं डाला गया):
mysql> insert into DemoTable1373 values(); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable1373 values(); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable1373 values(); Query OK, 1 row affected (0.18 sec)
सभी रिकॉर्ड देखें:
mysql> select * from DemoTable1373;
आउटपुट:
+-----------+----------------+ | StudentId | StudentDetails | +-----------+----------------+ | 1 | NULL | | 2 | NULL | | 3 | NULL | +-----------+----------------+ 3 rows in set (0.00 sec)
MySQL फील्ड को JSON फॉर्मेट में अपडेट करने की क्वेरी:
mysql> update DemoTable1373 set StudentDetails=concat("{", "StudentName:", " John ,", "StudentAge:", 21, ",", "StudentCountryName:", "US", "}"); Query OK, 3 rows affected (0.14 sec) Rows matched: 3 Changed: 3 Warnings: 0
फिर से रिकॉर्ड जांचें:
mysql> select * from DemoTable1373;
आउटपुट:
+-----------+---------------------------------------------------------------+ | StudentId | StudentDetails | +-----------+---------------------------------------------------------------+ | 1 | {StudentName: John , StudentAge:21, StudentCountryName: US} | | 2 | {StudentName: John , StudentAge:21, StudentCountryName: US} | | 3 | {StudentName: John , StudentAge:21, StudentCountryName: US} | +-----------+---------------------------------------------------------------+ 3 rows in set (0.00 sec)
नोट: यह मैन्युअल CONCAT के साथ JSON-जैसा स्ट्रिंग बनाता है। MySQL 5.7+ में JSON डेटा प्रकार और JSON_OBJECT(), JSON_ARRAY() फंक्शन हैं जो उचित JSON बनाने के लिए बेहतर हैं। उदाहरण: UPDATE t SET col = JSON_OBJECT('name', 'John', 'age', 21, 'country', 'US');