Showing posts with label json. Show all posts
Showing posts with label json. Show all posts

Thursday, June 29, 2017

How create json format with group-concat mysql | How to put JSON into a column data if sub-query returns more than 1 row in MySQL | Optimized way of getting subqueries at once using JSON

How create json format with group-concat mysql |  How to put JSON into a column data if sub-query returns more than 1 row in MySQL | Optimized way of getting subqueries at once using JSON.

A bit convoluted, but you could create JSON objects for each row, concatenate them using GROUP_CONCAT and cast the result (wrapped in [] to make it an array) to JSON;

Below is the full example:


<?php
define("DB_DEFAULT_HOST", "localhost");
define("DB_DEFAULT_DATABASE", "test71");
define("DB_DEFAULT_USER", "root");
define("DB_DEFAULT_PASSWORD", "");

$dbh = null;
try {
    $dbh = new PDO(
        "mysql:host=" . DB_DEFAULT_HOST . ";dbname=" . DB_DEFAULT_DATABASE,
        DB_DEFAULT_USER,
        DB_DEFAULT_PASSWORD
    );
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh->beginTransaction();

    $query =
        "SELECT
            s.name AS Name, s.roll AS Roll,
            CONCAT(
              '[', COALESCE(
                GROUP_CONCAT(
                  CONCAT('{', 
                    '\"ExamName\":', '\"', HEX(CONVERT(e.subject USING utf32)), '\"',
                    ',\"Score\":', '\"', e.score, '\"',
                  '}')
                  SEPARATOR ','
                ), ''
              ), ']'
            ) AS ExamsRaw
        
        FROM student AS s
          LEFT JOIN exams AS e ON e.student_id=s.id
        
        GROUP BY s.id";

    $students = $dbh->query($query)->fetchAll(PDO::FETCH_OBJ);
    foreach ($students as $entity) {
        $entity->Exams = array();
        foreach (json_decode($entity->ExamsRaw) as $group) {
            $group->ExamName = hexToStr($group->ExamName);
            array_push($entity->Exams, $group);
        }
        unset($entity->ExamsRaw);
    }
    echo "<pre>";
    print_r($students);
    echo "</pre>";
}
catch (\Exception $ex) {
    echo "MySQL_Error=" . $ex->getMessage();
    $dbh->rollBack();
}

function hexToStr($hex)
{
    $string = '';
    for ($index = 0; $index < strlen($hex) - 1; $index += 2) {
        $string .= chr(hexdec($hex[$index] . $hex[$index + 1]));
    }
    return $string;
}

And below is the output of above example code block:


Array
(
    [0] => stdClass Object
        (
            [Name] => Prtiom First Year
            [Roll] => P1
            [Exams] => Array
                (
                    [0] => stdClass Object
                        (
                            [ExamName] => ©|æ|þ|½|±|®|¶
                            [Score] => 1.12
                        )

                    [1] => stdClass Object
                        (
                            [ExamName] => Subject 2   
                            [Score] => 2.54
                        )

                    [2] => stdClass Object
                        (
                            [ExamName] =>  ¡¢£¤¥¦§¨©
                            [Score] => 1.98
                        )

                )

        )

    [1] => stdClass Object
        (
            [Name] => Pritom Second Year
            [Roll] => P2
            [Exams] => Array
                (
                    [0] => stdClass Object
                        (
                            [ExamName] => Subject 2
                            [Score] => 4.00
                        )

                    [1] => stdClass Object
                        (
                            [ExamName] => Subject 3
                            [Score] => 3.00
                        )

                )

        )

)

Aware that mysql group function max length is by default 1024 characters. If your group function more than 1024 then you have to change limit of mysql group function using following query:

This is for current session:
SET SESSION group_concat_max_len = 1000000;

But if you want it global scope, then do following:
SET GLOBAL group_concat_max_len = 1000000;

Monday, July 25, 2016

Parse JSON in Salesforce


public class CommonJsonParser {
    public cls_Parent[] parentList;
    class cls_Parent {
        public Integer intType;
        public Double doubleType;
        public String stringType;
        public cls_Child[] childList;
    }
    class cls_Child {
        public Integer param_1;
        public String param_2;
    }
    public static CommonJsonParser parse(String json){
        return (CommonJsonParser) System.JSON.deserialize(json, CommonJsonParser.class);
    }

    public static String test() {
        String json = '{"parentList":[' + 
            '{"intType":1,"doubleType":1.5,"stringType":"String_1",' + 
            '"childList":[' + 
                '{"param_1":1,"param_2":"String_100"},' + 
                '{"param_1":5,"param_2":"String_101"}]}'+
            ',{"intType":2,"doubleType":2.5,"stringType":"String_2",' + 
            '"childList":[' + 
                '{"param_1":6,"param_2":"String_102"},' + 
                '{"param_1":2,"param_2":"String_103"},' + 
                '{"param_1":1,"param_2":"String_104"}]}]}';
        CommonJsonParser obj = parse(json);
        
        String output = '';
        
        for(cls_Parent cParent : obj.parentList) {
            output += '<br/>';
            output += '[[ Integer_Value=' + cParent.intType;
            output += ', Double_Value=' + cParent.doubleType;
            output += ', String_Value=' + cParent.stringType + ' ]]';
            
            for(cls_Child cChild: cParent.childList) {
                output += '<br/>&nbsp;&nbsp;&nbsp;&nbsp;Param_1=' + cChild.param_1;
                output += ', Param_2=' + cChild.param_2;
            }
        }
        
        return output;
    }
}
Output would be like this:

[[ Integer_Value=1, Double_Value=1.5, String_Value=String_1 ]]
    Param_1=1, Param_2=String_100
    Param_1=5, Param_2=String_101
[[ Integer_Value=2, Double_Value=2.5, String_Value=String_2 ]]
    Param_1=6, Param_2=String_102
    Param_1=2, Param_2=String_103
    Param_1=1, Param_2=String_104 

Friday, July 25, 2014

Java: Convert Map/List to JSON Using google-gson


package com.pkm.com.java.json;

import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainClass {
    public static void main(String[] args) {
        Map dataMap = new HashMap();
        dataMap.put("args1", "Args 1");
        dataMap.put("args2", "Args 2");
        dataMap.put("args3", "Args 3");
        dataMap.put("args4", "Args 4");
        
        Map subMap = new HashMap();
        subMap.put("subArgs1", "Sub Args 1");
        subMap.put("subArgs2", "Sub Args 2");
        subMap.put("subArgs3", "Sub Args 3");
        dataMap.put("args5", subMap);
        
        List subList = new ArrayList();
        subList.add("List 1");
        subList.add("List 2");
        subList.add("List 3");
        subList.add(subMap);
        dataMap.put("args6", subList);
        
        Gson gson = new Gson();
        String json = gson.toJson(dataMap);
        System.out.println("json = " + json);
        
        Map dataMapFromJSONString = gson.fromJson(json, Map.class);
        display(dataMapFromJSONString, 0);
    }
    
    private static void display(Map map, Integer depth) {
        for (Object key : map.keySet()) {
            Object value = map.get(key.toString());
            if (value == null) {
                displaySpace(depth);
                System.out.println(key + ": <NULL>");
            }
            else if (value instanceof Map) {
                displaySpace(depth);
                System.out.println(key + ": ");
                Integer nextDepth = depth + 1;
                display((Map) value, nextDepth);
            }
            else if (value instanceof List) {
                displaySpace(depth);
                System.out.println(key + ": ");
                Integer nextDepth = depth + 1;
                display((List) value, nextDepth);
            }
            else {
                displaySpace(depth);
                System.out.println(key + ": " + value);
            }
        }
    }
    
    private static void display(List list, Integer depth) {
        for (Integer index = 0; index < list.size(); index++) {
            Object value = list.get(index);
            if (value == null) {
                displaySpace(depth);
                System.out.println("<NULL>");
            }
            else if (value instanceof Map) {
                displaySpace(depth);
                System.out.print("---->\n");
                Integer nextDepth = depth + 1;
                display((Map) value, nextDepth);
            }
            else if (value instanceof List) {
                displaySpace(depth);
                System.out.print("---->\n");
                Integer nextDepth = depth + 1;
                display((List) value, nextDepth);
            }
            else {
                displaySpace(depth);
                System.out.println(value);
            }
        }
    }
    
    private static void displaySpace(Integer depth) {
        for (Integer index = 0; index < depth; index++) {
            System.out.print("    ");
        }
    }
}

Google gson link
Download full source code

Output:


JSON String = {"args5":{"subArgs1":"Sub Args 1","subArgs2":"Sub Args 2","subArgs3":"Sub Args 3"},"args6":["List 1","List 2","List 3",{"subArgs1":"Sub Args 1","subArgs2":"Sub Args 2","subArgs3":"Sub Args 3"}],"args3":"Args 3","args4":"Args 4","args1":"Args 1","args2":"Args 2"}

Data Display From JSON String:

args5: 
    subArgs1: Sub Args 1
    subArgs2: Sub Args 2
    subArgs3: Sub Args 3
args6: 
    List 1
    List 2
    List 3
    ---->
        subArgs1: Sub Args 1
        subArgs2: Sub Args 2
        subArgs3: Sub Args 3
args3: Args 3
args4: Args 4
args1: Args 1
args2: Args 2

Thursday, December 5, 2013

POSTing json data with php cURL


<?php
$params = array(
    "id" => 1,
    "name" => "Pritom Kumar Mondal"
);
$param = json_encode($params);
$ch   = curl_init("http://localhost/api_server/user");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($param))
);
$response = curl_exec($ch);
print_r($response);
?>

Wednesday, September 11, 2013

How to parse JSON in Java

JSON slurper which parses text or reader content into a data structure of lists and maps.

Example usage:
def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')

println "Name: "+result.person.name;
println "Age: "+result.person.age;
println "Pet Size: "+result.person.pets.size();
println "Pet[0]: "+result.person.pets[0];
println "Pet[1]: "+result.person.pets[1];

Output:
Name: Guillaume
Age: 33
Pet Size: 2
Pet[0]: dog
Pet[1]: cat
 
http://groovy.codehaus.org/gapi/groovy/json/JsonSlurper.html