Decoding Nested JSON in PHP

Decoding Nested JSON in PHP

By : user2955370
Date : November 22 2020, 10:38 AM
like below fixes the issue I suggest to pass it true as a parameter, it is easier to work with associative arrays than objects:
code :
$messages = json_decode($source, true);
foreach($messages as $message){
   $trainID = $message["body"]["train_id"];

Share : facebook icon twitter icon
decoding nested json objects in go

decoding nested json objects in go

By : thegaw
Date : March 29 2020, 07:55 AM
hop of those help? You're doing it the hard way by using interface{} and not taking advantage of what encoding/json gives you.
I'd do it something like this (note I assumed there was an error with the type of the "gtAns" field and I made it a boolean, you don't give enough information to know what to do with the "RT" field):
code :
package main

import (

const input = `{
    "0":{"index":0,"word":"WORD 1","Time":3000,"keyboard":true,"train":true,"type":"A"},
    "1":{"index":1,"word":"WORD 2","Time":3000,"keyboard":true,"train":true,"type":"A"}

type Whatever struct {
        User struct {
                Gender Gender   `json:"gender"`
                Age    Range    `json:"age"`
                ID     IDString `json:"id"`
        } `json:"user"`
        Trials map[string]struct {
                Index int    `json:"index"`
                Word  string `json:"word"`
                Time  int    // should this be a time.Duration?
                Train bool   `json:"train"`
                Type  string `json:"type"`
        } `json:"trials"`
        Answers map[string][]struct {
                Answer    int             `json:"ans"`
                RT        json.RawMessage // ??? what type is this
                GotAnswer bool            `json:"gtAns"`
                Correct   int             `json:"correct"`
        } `json:"answers"`

// Using some custom types to show custom marshalling:

type IDString string // TODO custom unmarshal and format/error checking

type Gender int

const (
        Male Gender = iota

func (g *Gender) UnmarshalJSON(b []byte) error {
        var s string
        err := json.Unmarshal(b, &s)
        if err != nil {
                return err
        switch strings.ToLower(s) {
        case "male":
                *g = Male
        case "female":
                *g = Female
                return fmt.Errorf("invalid gender %q", s)
        return nil
func (g Gender) MarshalJSON() ([]byte, error) {
        switch g {
        case Male:
                return []byte(`"male"`), nil
        case Female:
                return []byte(`"female"`), nil
                return nil, fmt.Errorf("invalid gender %v", g)

type Range struct{ Min, Max int }

func (r *Range) UnmarshalJSON(b []byte) error {
        // XXX could be improved
        _, err := fmt.Sscanf(string(b), `"%d-%d"`, &r.Min, &r.Max)
        return err
func (r Range) MarshalJSON() ([]byte, error) {
        return []byte(fmt.Sprintf(`"%d-%d"`, r.Min, r.Max)), nil
        // Or:
        b := make([]byte, 0, 8)
        b = append(b, '"')
        b = strconv.AppendInt(b, int64(r.Min), 10)
        b = append(b, '-')
        b = strconv.AppendInt(b, int64(r.Max), 10)
        b = append(b, '"')
        return b, nil

func fromJSON(r io.Reader) (Whatever, error) {
        var x Whatever
        dec := json.NewDecoder(r)
        err := dec.Decode(&x)
        return x, err

func main() {
        // Use http.Get or whatever to get an io.Reader,
        // (e.g. response.Body).
        // For playground, substitute a fixed string
        r := strings.NewReader(input)

        // If you actually had a string or []byte:
        //     var x Whatever
        //     err := json.Unmarshal([]byte(input), &x)

        x, err := fromJSON(r)
        if err != nil {
        fmt.Printf("%+v\n", x)

        b, err := json.MarshalIndent(x, "", "  ")
        if err != nil {
        fmt.Printf("Re-marshalled: %s\n", b)

typed nested json decoding in go

typed nested json decoding in go

By : Salah Ka
Date : March 29 2020, 07:55 AM
hope this fix your issue All struct fields you want to marshal should start with uppercase letter (be public). This works https://play.golang.org/p/ReCp3BAfTb
Decoding nested JSON structures

Decoding nested JSON structures

By : edgargrs
Date : March 29 2020, 07:55 AM
Any of those help I would start by decoding the authors, and then use andThen to pass the authors Dict into decodeContent. You can then use Decode.map to convert to author name into a lookup in the authors Dict.
code :
decoder =
    (field "authors" <| Decode.dict <| authorDecoder)
        |> Decode.andThen configDecoder

configDecoder authors =
    Decode.map2 Config
        (field "posts" <| Decode.list <| decodeContent Post authors)
        (field "pages" <| Decode.list <| decodeContent Page authors)

decodeContent contentType authors =
    Decode.map8 Content
        -- …
        (field "author" (string |> Decode.map (\name -> Dict.get name authors)))
        -- …
Swift Decoding nested JSON

Swift Decoding nested JSON

By : user49547
Date : March 29 2020, 07:55 AM
should help you out The JSON being returned by that API gives you an array, not a dictionary, but you're telling the JSONDecoder to expect a dictionary type. Change that line to:
let currencies = try decoder.decode([CurrencyDataStore].self, from: data)
Decoding a nested JSON Swift

Decoding a nested JSON Swift

By : user1550431
Date : March 29 2020, 07:55 AM
will help you Aside from posting the JSON Code itself, it would be useful to actually show an attempt as to how you have attempted to decode it as well ^_________^.
Anyway, the best way to tackle this issue is to use custom Structs and the Decodable Protocol to handle the JSON response.
code :
/// The Initial Response From The Server
struct Response: Decodable {
    let status: Int
    let data: ResponseData

/// The Data Object
struct ResponseData: Decodable{
    let date: String
    let featured: [Product]
    let daily: [Product]
/// The Product Structure
struct Product: Decodable{
    let id: String
    let name: String
    let price: String
    let priceIcon: String
    let priceIconLink: String
    let images: ProductImages
    let rarity: String
    let type: String
    let readableType: String
/// The Data From The Product Images Dictionary
struct ProductImages: Decodable{
    let icon: String
    let png: String
    let gallery: String

    ///The Featured Variable For The Product Images Can Contain Either A String Or A Boolean Value
    let featured: FeaturedType

/// Featured Type Returns A String Of Either The Boolean Value Or The Link To The JPG
struct FeaturedType : Codable {

    let formatted: String

    init(from decoder: Decoder) throws {

        let container =  try decoder.singleValueContainer()

        do {
            //1. If We Get A Standard Response We Have A String
            let stringResult = try container.decode(String.self)
            formatted = stringResult
        } catch {
            //2. On Occassions We Get An Bool
            let boolResult = try container.decode(Bool.self)
            formatted = String(boolResult)

/// Loads & Decodes The JSON File
func retreiveJSON(){

    //1. Load The JSON File From The Main Bundle
    guard let jsonURL = Bundle.main.url(forResource: "sample", withExtension: ".json") else { return }

        //2. Get The Data From The URL
        let data = try Data(contentsOf: jsonURL)

        //3. Decode The JSON
        let jsonData = try JSONDecoder().decode(Response.self, from: data)

        //4. Extract The Data

        print("Error Processing JSON == \(error)")
/// Extracts The Daily & Featured Products From The JSON
/// - Parameter jsonData: Response
func extractDataFrom(_ jsonData: Response){

    //1. Get The Daily Products
    let dailyProducts = jsonData.data.daily

    dailyProducts.forEach { (product) in


    //2. Get The Featured Products
    let featuredProducts = jsonData.data.featured

    featuredProducts.forEach { (product) in

var featuredProducts = [Product]()
var dailyProducts = [Product]()
 let dailyProducts
 let featuredProducts
dailyProducts = jsonData.data.daily
featuredProducts = jsonData.data.featured
Related Posts Related Posts :
  • Curl PHP cannot display amazon
  • Symfony, getters and setters vs magic methods
  • Using 'continue' PHP instruction outside the loop
  • AJAX POST return data not appearing
  • Can I query relations using an INNER JOIN instead of two queries in Eloquent?
  • Looping through dynamic form fields and inserting into database
  • My php code can't select mysql auto_increment value
  • Store Angularjs form data in database using php
  • I want to run my sh file continuously even if I close my Putty connection
  • file_get_contents equivalent for gzipped files
  • Include PHP file with jQuery
  • php curl headers do not return from website?
  • How to find out, if facebook ID is a user, group or page
  • Connect webhost database to android database
  • preg_match get div content with class
  • Upload multiple files in Laravel 4
  • Count array numbers in multidimensional array
  • PHP Date diff with a difference
  • Search Customer by custom field in Netsuite
  • Is it possible to hide/encode/encrypt php source code and let others have the system?
  • list items to be displayed using php code and array
  • check if row exists mysqli
  • PHP errors loading MySQL
  • setup PostgreSQL with Laravel in MAMP
  • PHP - CodeIgniter Notifications
  • Encrypting a password column in a SQL database
  • New to PHP, trying to extract information from another website
  • JavaScript AmChart to Image for Email
  • Is javascript validation enough to keep my forms secure?
  • Regex extract variables from [shortcode]
  • Download a .mp3 link and save it to computer with PHP
  • Error with the ereg_replace
  • Getting the fields attached to a bundle of an entity in Drupal
  • Php how to check multiple times (within `foreach`) if values from array exists in mysql?
  • MySQL and PHP parsing strange string
  • Pull specific data from multidimensional associative array
  • How to get the original URI extension using PHP Tonic?
  • Upload videos and images from Android to PHP server?
  • Unset a multidimensional array with another multidimensional array with values than key
  • Calling a user e-mail to add to a mailto link PHP
  • Why is override_function coming back as an undefined function
  • PHP mySQLi_fetch_all: iterate through each row
  • Using pow in php
  • What's wrong with my PHP Script? T_String issue
  • how to call a function of another file without including that file
  • is_rgb function in php
  • transform the numbers to letters using php
  • How to catch an exception from another class method PHP
  • PHP exec is blocked by ISP
  • PHP4 to PHP5 migration character encoding. latin1 vs utf8
  • Begin Transaction not defined
  • How much harm can a user do with xss on a page unique to them?
  • How to import data from a php file to javascript variable
  • PHP and Javascript - log complete workflow
  • When I echo !!! 0 it gives me a strange result
  • jquery ajax post dies after submit
  • How to upload file with curl on sftp server
  • Advanced search using a text input to search through only one category
  • Why do I get "Non-static method App\Models\Category::products() should not be called statically" in laravel
  • Stop notices from undefined indexes in arrays
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org