Deval Desai

Deval Desai

1586232540

Common JSON patterns in Haskell, Rust and TypeScript

A lot of web development is transforming JSON one way or another. In TypeScript/JavaScript this is straightforward, since JSON is built into the language. But can we also achieve good ergonomics in Haskell and Rust?

The comparisons we will see is not meant to show if one approach is better than another. Instead, it is intended to be a reference to become familiar with common patterns across multiple languages. Throughout this post we will utilize several tools and libraries.

The core of working with JSON in Haskell and Rust is covered by:

  • Aeson: a Haskell JSON serialization/deserialization library
  • Serde: a Rust JSON serialization/deserialization library.

The ergonomics is then improved in Haskell by grabbing one of the following options

We’ll go through typical use-cases seen in TypeScript/JavaScript codebases, and see how we can achieve the same in Haskell and Rust.

Table of Contents:

  • Preparation: Setting up our data
  • Comparison
    • Get a field
    • Get a nested field
    • Get an optional field
    • Update a field
    • Update a nested field
    • Update each item in a list

Preparation: Setting up our data

First we will setup our data structures and a few examples, which we will use throughout this post. Haskell and Rust requires a bit more ceremony, because we will use packages/crates. For TypeScript we use ts-node to run TypeScript in a REPL.

TypeScript

Let us first set up our reference Object in TypeScript. Save the following in house.ts (or check out typescript-json):

interface Address {
  country: string;
  address: string;
}

interface Person {
  id: number;
  firstname: string;
  lastname: string;
}

interface Household {
  id: number;
  people: Person[];
  address?: Address;
  alternativeAddress?: Address;
  owner: Person;
}

const addr: Address = { country: "Ocean", address: "Under the sea" };
const mom: Person = { id: 1, firstname: "Ariel", lastname: "Swanson" };
const dad: Person = { id: 2, firstname: "Triton", lastname: "Swanson" };
const son: Person = { id: 3, firstname: "Eric", lastname: "Swanson" };
const house: Household = {
  id: 1,
  people: [mom, dad, son],
  address: addr,
  // We omit `alternativeAddress` which is optional.
  owner: mom,
};

Haskell

The included snippet serves to give you an idea of the datastructures, types, and names that we will be working with.

The setups for each specific solution can be found in:

Check out src/House.hs for the data structures, and src/Main.hs for all the examples throughout this post.

data Address = Address
  { country :: String
  , address :: String
  }

data Person = Person
  { id :: Int
  , firstname :: String
  , lastname :: String
  }

data Household = Household
  { id :: Int
  , people :: [Person]
  , address :: Maybe Address
  , alternativeAddress :: Maybe Address
  , owner :: Person
  }

house = Household
  { id = 1
  , people = [mom, dad, son]
  , address = Just addr
  , alternativeAddress = Nothing
  , owner = mom
  }
  where
    addr = Address { country = "Ocean", address = "Under the sea" }
    mom = Person { id = 1, firstname = "Ariel", lastname = "Swanson" }
    dad = Person { id = 2, firstname = "Triton", lastname = "Swanson" }
    son = Person { id = 3, firstname = "Eric", lastname = "Swanson" }

To allow overlapping record fields, we use DuplicateRecordFields along with OverloadedLabels (only in the Lens version), and a bunch of other extensions for deriving things via generics.

Rust

The full setup can be found in rust-serde. Check out src/house.rs for the data structures, and src/main.rs for all the examples throughout this post.

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Address {
    pub country: String,
    pub address: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Person {
    pub id: u32,
    pub firstname: String,
    pub lastname: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Household {
    pub id: u32,
    pub people: Vec<Person>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address: Option<Address>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alternative_address: Option<Address>,
    pub owner: Person
}

pub fn house() -> Household {
    let addr = Address { country: "Ocean".to_string(), address: "Under the sea".to_string() };
    let mom = Person { id: 1, firstname: "Ariel".to_string(), lastname: "Swanson".to_string() };
    let dad = Person { id: 2, firstname: "Triton".to_string(), lastname: "Swanson".to_string() };
    let son = Person { id: 3, firstname: "Eric".to_string(), lastname: "Swanson".to_string() };
    Household {
        id: 1,
        people: vec![mom.clone(), dad, son],
        address: Some(addr),
        alternative_address: None,
        owner: mom
    }
}

Comparison

If you wish to following along, you can fire up a REPL for each approach.

💡 For the TypeScript and Rust versions, where we utilize mutability, we will clone the objects each time, to keep them consistent across examples.

TypeScript

$ cd typescript-json
$ npm i
$ npm run repl
> import data from './house'
> let newData

Haskell

$ cd haskell-lens
$ stack build
$ stack ghci
*Main Data>

Unfortunately GHC plugins doesn’t play nicely with ghci. We will instead build the project, so we can play around with the examples in src/Main.hs.

$ cd haskell-record-dot
$ stack build
$ # Open src/Main.hs in your editor
$ stack run

Rust

Since Rust doesn’t have a REPL, we will instead build the project, so we play around with the examples in src/main.rs.

$ cd rust-serde
$ cargo build
$ # Open src/main.rs in your editor
$ cargo run

Get a field

The first one is simple, we will get a value from our object.

First, our TypeScript version:

> data.house.owner
{ id: 1, firstname: 'Ariel', lastname: 'Swanson' }

Let’s see how we achieve this in Haskell with Lenses:

*Main Data> house ^. #owner
Person {id = 1, firstname = "Ariel", lastname = "Swanson"}

There’s probably already two unfamiliar pieces of syntax here.

The first, ^., comes from Lens and is the view function that we use as an accessor to the object/record. The second, the # prefix of #owner, comes from the OverloadedLabels extension, and allows us to have multiple record fields of the same name in scope.

Let’s see how we achieve this in Haskell with Record Dot Syntax:

house.owner
--> Person {id = 1, firstname = "Ariel", lastname = "Swanson"}

Finally, let’s check out Rust:

house.owner
--> Person { id: 1, firstname: "Ariel", lastname: "Swanson" }

Get a nested field

We slowly increase the difficulty, by accessing a nested field.

TypeScript:

> data.house.owner.firstname
'Ariel'

Haskell with Lenses:

*Main Data> house ^. #owner . #firstname
"Ariel"

Haskell with Record Dot Syntax:

house.owner.firstname
--> "Ariel"

Rust:

house.owner.firstname
--> "Ariel"

Get an optional field

How do we handle optional fields?

TypeScript:

// A field that exists.
> data.house.address.address
'Under the sea'

// A field that does *NOT* exist (throws exception.)
> data.house.alternativeAddress.address
TypeError: Cannot read property 'address' of undefined
    at ....

// A field that does *NOT* exist, using optional-chaining.
> data.house.alternativeAddress?.address
undefined

Optional chaining (?) is a great step forward for writing safer and cleaner code in JS/TS.

Haskell with Lenses:

-- Return the value in a Maybe.
*Main Data> house ^. #address
Just (Address {country = "Ocean", address = "Under the sea"})

-- A field on an object that exists.
*Main Data> house ^. #address . #_Just . #address
"Under the sea"

-- A field on an object that does *NOT* exist (falls back to an empty value.)
*Main Data> house ^. #alternativeAddress . #_Just . #address
""

#_Just from Lens gives us handy access to fields wrapped in Maybes, with a fallback value.

Haskell with Record Dot Syntax:

-- Return the value in a Maybe.
house.address
--> Just (Address {country = "Ocean", address = "Under the sea"})

-- A field on an object that exists.
maybe "" (.address) house.address
--> "Under the sea"

-- A field on an object that does *NOT* exist (falls back to an empty value.)
maybe "" (.address) house.alternativeAddress
--> ""

We end up writing more regular code to dive into the Maybe value, by using maybe5 to proceed or fallback to a default value.

Rust:

// Return the value in an Option.
house.address
--> Some(Address { country: "Ocean", address: "Under the sea" })

// A field on an object that exists.
house.address.and_then(|a| Some(a.address)).unwrap_or("".to_string())
--> "Under the sea"

// A field on an object that does *NOT* exist (falls back to an empty value.)
house.alternative_address.and_then(|a| Some(a.address)).unwrap_or("".to_string())
--> ""

We utilize and_then a bit like maybe, passing a function to act on our value if it’s Some, and then creating a default case with unwrap_or.

Update a field

We’ll start with updating a non-nested field.

TypeScript:

> newData = JSON.parse(JSON.stringify(data)) // Clone our data object.
> const newAriel = { id: 4, firstname: 'New Ariel', lastname: 'Swandóttir' }
> newData.house.owner = newAriel
{ id: 4, firstname: 'New Ariel', lastname: 'Swandóttir' }

Haskell with Lenses:

*Main Data> let newAriel = Person { id = 4, firstname = "New Ariel", lastname = "Swanson" }
*Main Data> house & #owner .~ newAriel
Household { {- Full Household object... -} }

We add two new pieces of syntax here. The & is a reverse application operator, but for all intents and purposes think of it as the ^. for setters. Finally, .~ is what allows us to actually set our value.

Haskell with Record Dot Syntax:

let newAriel = Person { id = 4, firstname = "New Ariel", lastname = "Swanson" }
house{ owner = newAriel}
--> Household { {- Full Household object... -} }

Pretty neat. Note that the lack of spacing in house{ is intentional.

Rust:

let mut new_house = house.clone();
let new_ariel = Person { id: 4, firstname: "New Ariel".to_string(), lastname: "Swanson".to_string() };
new_house.owner = new_ariel;
--> Household { /* Full Household object... */ }

We use Rust’s Struct Update syntax, .., which works much like the spread syntax (...) in JavaScript.

Update a nested field

Now it gets a bit more tricky.

TypeScript:

> newData = JSON.parse(JSON.stringify(data)) // Clone our data object.
> newData.house.owner.firstname = 'New Ariel'
'New Ariel'

Haskell with Lenses:

*Main Data> house & #owner . #firstname .~ "New Ariel"
Household { {- Full Household object... -} }

Note that we mix & and . to dig deeper in the object/record, much like accessing a nested field.

Haskell with Record Dot Syntax:

house{ owner.firstname = "New Ariel"}
--> Household { {- Full Household object... -} }

Note that the lack of spacing in house{ is actually important, at least in the current state of RecordDotSyntax.

Rust:

let mut new_house = house.clone();
new_house.owner.firstname = "New Ariel".to_string();
--> Household { /* Full Household object... */ }

Update each item in a list

Let’s work a bit on the people list in our household. We’ll make those first names a bit more fresh.

TypeScript:

> newData = JSON.parse(JSON.stringify(data)) // Clone our data object.
> newData.house.people.forEach(person => { person.firstname = `Fly ${person.firstname}` })
> newData.house.people
[
  { id: 1, firstname: 'Fly Ariel', lastname: 'Swanson' },
  { id: 2, firstname: 'Fly Triton', lastname: 'Swanson' },
  { id: 3, firstname: 'Fly Eric', lastname: 'Swanson' }
]

Haskell with Lenses:

-- You can usually also use `traverse` instead of `mapped` here.
*Main Data> house & #people . mapped . #firstname %~ ("Fly " <>)
Household { {- Full Household object... -} }

mapped allows us to map a function over all the values in #people.

Haskell with Record Dot Syntax:

house{ people = map (\p -> p{firstname = "Fly " ++ p.firstname}) house.people}
--> Household { {- Full Household object... -} }

Using map feels very natural, and is quite close to the regular code you would write in Haskell.

Rust:

let mut new_house = house.clone();
new_house.people.iter_mut().for_each(|p| p.firstname = format!("Fly {}", p.firstname));
--> Household { /* Full Household object... */ }

Have other common patterns you’d like to see? Feel like some of the approaches could be improved? Leave a comment, and I will try to expand this list to be more comprehensive!

Originally published at https://codetalk.io

#json #haskell #rust #typescript #javascript

What is GEEK

Buddha Community

Common JSON patterns in Haskell, Rust and TypeScript
Deval Desai

Deval Desai

1586232540

Common JSON patterns in Haskell, Rust and TypeScript

A lot of web development is transforming JSON one way or another. In TypeScript/JavaScript this is straightforward, since JSON is built into the language. But can we also achieve good ergonomics in Haskell and Rust?

The comparisons we will see is not meant to show if one approach is better than another. Instead, it is intended to be a reference to become familiar with common patterns across multiple languages. Throughout this post we will utilize several tools and libraries.

The core of working with JSON in Haskell and Rust is covered by:

  • Aeson: a Haskell JSON serialization/deserialization library
  • Serde: a Rust JSON serialization/deserialization library.

The ergonomics is then improved in Haskell by grabbing one of the following options

We’ll go through typical use-cases seen in TypeScript/JavaScript codebases, and see how we can achieve the same in Haskell and Rust.

Table of Contents:

  • Preparation: Setting up our data
  • Comparison
    • Get a field
    • Get a nested field
    • Get an optional field
    • Update a field
    • Update a nested field
    • Update each item in a list

Preparation: Setting up our data

First we will setup our data structures and a few examples, which we will use throughout this post. Haskell and Rust requires a bit more ceremony, because we will use packages/crates. For TypeScript we use ts-node to run TypeScript in a REPL.

TypeScript

Let us first set up our reference Object in TypeScript. Save the following in house.ts (or check out typescript-json):

interface Address {
  country: string;
  address: string;
}

interface Person {
  id: number;
  firstname: string;
  lastname: string;
}

interface Household {
  id: number;
  people: Person[];
  address?: Address;
  alternativeAddress?: Address;
  owner: Person;
}

const addr: Address = { country: "Ocean", address: "Under the sea" };
const mom: Person = { id: 1, firstname: "Ariel", lastname: "Swanson" };
const dad: Person = { id: 2, firstname: "Triton", lastname: "Swanson" };
const son: Person = { id: 3, firstname: "Eric", lastname: "Swanson" };
const house: Household = {
  id: 1,
  people: [mom, dad, son],
  address: addr,
  // We omit `alternativeAddress` which is optional.
  owner: mom,
};

Haskell

The included snippet serves to give you an idea of the datastructures, types, and names that we will be working with.

The setups for each specific solution can be found in:

Check out src/House.hs for the data structures, and src/Main.hs for all the examples throughout this post.

data Address = Address
  { country :: String
  , address :: String
  }

data Person = Person
  { id :: Int
  , firstname :: String
  , lastname :: String
  }

data Household = Household
  { id :: Int
  , people :: [Person]
  , address :: Maybe Address
  , alternativeAddress :: Maybe Address
  , owner :: Person
  }

house = Household
  { id = 1
  , people = [mom, dad, son]
  , address = Just addr
  , alternativeAddress = Nothing
  , owner = mom
  }
  where
    addr = Address { country = "Ocean", address = "Under the sea" }
    mom = Person { id = 1, firstname = "Ariel", lastname = "Swanson" }
    dad = Person { id = 2, firstname = "Triton", lastname = "Swanson" }
    son = Person { id = 3, firstname = "Eric", lastname = "Swanson" }

To allow overlapping record fields, we use DuplicateRecordFields along with OverloadedLabels (only in the Lens version), and a bunch of other extensions for deriving things via generics.

Rust

The full setup can be found in rust-serde. Check out src/house.rs for the data structures, and src/main.rs for all the examples throughout this post.

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Address {
    pub country: String,
    pub address: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Person {
    pub id: u32,
    pub firstname: String,
    pub lastname: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Household {
    pub id: u32,
    pub people: Vec<Person>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address: Option<Address>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alternative_address: Option<Address>,
    pub owner: Person
}

pub fn house() -> Household {
    let addr = Address { country: "Ocean".to_string(), address: "Under the sea".to_string() };
    let mom = Person { id: 1, firstname: "Ariel".to_string(), lastname: "Swanson".to_string() };
    let dad = Person { id: 2, firstname: "Triton".to_string(), lastname: "Swanson".to_string() };
    let son = Person { id: 3, firstname: "Eric".to_string(), lastname: "Swanson".to_string() };
    Household {
        id: 1,
        people: vec![mom.clone(), dad, son],
        address: Some(addr),
        alternative_address: None,
        owner: mom
    }
}

Comparison

If you wish to following along, you can fire up a REPL for each approach.

💡 For the TypeScript and Rust versions, where we utilize mutability, we will clone the objects each time, to keep them consistent across examples.

TypeScript

$ cd typescript-json
$ npm i
$ npm run repl
> import data from './house'
> let newData

Haskell

$ cd haskell-lens
$ stack build
$ stack ghci
*Main Data>

Unfortunately GHC plugins doesn’t play nicely with ghci. We will instead build the project, so we can play around with the examples in src/Main.hs.

$ cd haskell-record-dot
$ stack build
$ # Open src/Main.hs in your editor
$ stack run

Rust

Since Rust doesn’t have a REPL, we will instead build the project, so we play around with the examples in src/main.rs.

$ cd rust-serde
$ cargo build
$ # Open src/main.rs in your editor
$ cargo run

Get a field

The first one is simple, we will get a value from our object.

First, our TypeScript version:

> data.house.owner
{ id: 1, firstname: 'Ariel', lastname: 'Swanson' }

Let’s see how we achieve this in Haskell with Lenses:

*Main Data> house ^. #owner
Person {id = 1, firstname = "Ariel", lastname = "Swanson"}

There’s probably already two unfamiliar pieces of syntax here.

The first, ^., comes from Lens and is the view function that we use as an accessor to the object/record. The second, the # prefix of #owner, comes from the OverloadedLabels extension, and allows us to have multiple record fields of the same name in scope.

Let’s see how we achieve this in Haskell with Record Dot Syntax:

house.owner
--> Person {id = 1, firstname = "Ariel", lastname = "Swanson"}

Finally, let’s check out Rust:

house.owner
--> Person { id: 1, firstname: "Ariel", lastname: "Swanson" }

Get a nested field

We slowly increase the difficulty, by accessing a nested field.

TypeScript:

> data.house.owner.firstname
'Ariel'

Haskell with Lenses:

*Main Data> house ^. #owner . #firstname
"Ariel"

Haskell with Record Dot Syntax:

house.owner.firstname
--> "Ariel"

Rust:

house.owner.firstname
--> "Ariel"

Get an optional field

How do we handle optional fields?

TypeScript:

// A field that exists.
> data.house.address.address
'Under the sea'

// A field that does *NOT* exist (throws exception.)
> data.house.alternativeAddress.address
TypeError: Cannot read property 'address' of undefined
    at ....

// A field that does *NOT* exist, using optional-chaining.
> data.house.alternativeAddress?.address
undefined

Optional chaining (?) is a great step forward for writing safer and cleaner code in JS/TS.

Haskell with Lenses:

-- Return the value in a Maybe.
*Main Data> house ^. #address
Just (Address {country = "Ocean", address = "Under the sea"})

-- A field on an object that exists.
*Main Data> house ^. #address . #_Just . #address
"Under the sea"

-- A field on an object that does *NOT* exist (falls back to an empty value.)
*Main Data> house ^. #alternativeAddress . #_Just . #address
""

#_Just from Lens gives us handy access to fields wrapped in Maybes, with a fallback value.

Haskell with Record Dot Syntax:

-- Return the value in a Maybe.
house.address
--> Just (Address {country = "Ocean", address = "Under the sea"})

-- A field on an object that exists.
maybe "" (.address) house.address
--> "Under the sea"

-- A field on an object that does *NOT* exist (falls back to an empty value.)
maybe "" (.address) house.alternativeAddress
--> ""

We end up writing more regular code to dive into the Maybe value, by using maybe5 to proceed or fallback to a default value.

Rust:

// Return the value in an Option.
house.address
--> Some(Address { country: "Ocean", address: "Under the sea" })

// A field on an object that exists.
house.address.and_then(|a| Some(a.address)).unwrap_or("".to_string())
--> "Under the sea"

// A field on an object that does *NOT* exist (falls back to an empty value.)
house.alternative_address.and_then(|a| Some(a.address)).unwrap_or("".to_string())
--> ""

We utilize and_then a bit like maybe, passing a function to act on our value if it’s Some, and then creating a default case with unwrap_or.

Update a field

We’ll start with updating a non-nested field.

TypeScript:

> newData = JSON.parse(JSON.stringify(data)) // Clone our data object.
> const newAriel = { id: 4, firstname: 'New Ariel', lastname: 'Swandóttir' }
> newData.house.owner = newAriel
{ id: 4, firstname: 'New Ariel', lastname: 'Swandóttir' }

Haskell with Lenses:

*Main Data> let newAriel = Person { id = 4, firstname = "New Ariel", lastname = "Swanson" }
*Main Data> house & #owner .~ newAriel
Household { {- Full Household object... -} }

We add two new pieces of syntax here. The & is a reverse application operator, but for all intents and purposes think of it as the ^. for setters. Finally, .~ is what allows us to actually set our value.

Haskell with Record Dot Syntax:

let newAriel = Person { id = 4, firstname = "New Ariel", lastname = "Swanson" }
house{ owner = newAriel}
--> Household { {- Full Household object... -} }

Pretty neat. Note that the lack of spacing in house{ is intentional.

Rust:

let mut new_house = house.clone();
let new_ariel = Person { id: 4, firstname: "New Ariel".to_string(), lastname: "Swanson".to_string() };
new_house.owner = new_ariel;
--> Household { /* Full Household object... */ }

We use Rust’s Struct Update syntax, .., which works much like the spread syntax (...) in JavaScript.

Update a nested field

Now it gets a bit more tricky.

TypeScript:

> newData = JSON.parse(JSON.stringify(data)) // Clone our data object.
> newData.house.owner.firstname = 'New Ariel'
'New Ariel'

Haskell with Lenses:

*Main Data> house & #owner . #firstname .~ "New Ariel"
Household { {- Full Household object... -} }

Note that we mix & and . to dig deeper in the object/record, much like accessing a nested field.

Haskell with Record Dot Syntax:

house{ owner.firstname = "New Ariel"}
--> Household { {- Full Household object... -} }

Note that the lack of spacing in house{ is actually important, at least in the current state of RecordDotSyntax.

Rust:

let mut new_house = house.clone();
new_house.owner.firstname = "New Ariel".to_string();
--> Household { /* Full Household object... */ }

Update each item in a list

Let’s work a bit on the people list in our household. We’ll make those first names a bit more fresh.

TypeScript:

> newData = JSON.parse(JSON.stringify(data)) // Clone our data object.
> newData.house.people.forEach(person => { person.firstname = `Fly ${person.firstname}` })
> newData.house.people
[
  { id: 1, firstname: 'Fly Ariel', lastname: 'Swanson' },
  { id: 2, firstname: 'Fly Triton', lastname: 'Swanson' },
  { id: 3, firstname: 'Fly Eric', lastname: 'Swanson' }
]

Haskell with Lenses:

-- You can usually also use `traverse` instead of `mapped` here.
*Main Data> house & #people . mapped . #firstname %~ ("Fly " <>)
Household { {- Full Household object... -} }

mapped allows us to map a function over all the values in #people.

Haskell with Record Dot Syntax:

house{ people = map (\p -> p{firstname = "Fly " ++ p.firstname}) house.people}
--> Household { {- Full Household object... -} }

Using map feels very natural, and is quite close to the regular code you would write in Haskell.

Rust:

let mut new_house = house.clone();
new_house.people.iter_mut().for_each(|p| p.firstname = format!("Fly {}", p.firstname));
--> Household { /* Full Household object... */ }

Have other common patterns you’d like to see? Feel like some of the approaches could be improved? Leave a comment, and I will try to expand this list to be more comprehensive!

Originally published at https://codetalk.io

#json #haskell #rust #typescript #javascript

Brandon  Adams

Brandon Adams

1625637060

What is JSON? | JSON Objects and JSON Arrays | Working with JSONs Tutorial

In this video, we work with JSONs, which are a common data format for most web services (i.e. APIs). Thank you for watching and happy coding!

Need some new tech gadgets or a new charger? Buy from my Amazon Storefront https://www.amazon.com/shop/blondiebytes

What is an API?
https://youtu.be/T74OdSCBJfw

JSON Google Extension
https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa?hl=en

Endpoint Example
http://maps.googleapis.com/maps/api/geocode/json?address=13+East+60th+Street+New+York,+NY

Check out my courses on LinkedIn Learning!
REFERRAL CODE: https://linkedin-learning.pxf.io/blondiebytes
https://www.linkedin.com/learning/instructors/kathryn-hodge

Support me on Patreon!
https://www.patreon.com/blondiebytes

Check out my Python Basics course on Highbrow!
https://gohighbrow.com/portfolio/python-basics/

Check out behind-the-scenes and more tech tips on my Instagram!
https://instagram.com/blondiebytes/

Free HACKATHON MODE playlist:
https://open.spotify.com/user/12124758083/playlist/6cuse5033woPHT2wf9NdDa?si=VFe9mYuGSP6SUoj8JBYuwg

MY FAVORITE THINGS:
Stitch Fix Invite Code: https://www.stitchfix.com/referral/10013108?sod=w&som=c
FabFitFun Invite Code: http://xo.fff.me/h9-GH
Uber Invite Code: kathrynh1277ue
Postmates Invite Code: 7373F
SoulCycle Invite Code: https://www.soul-cycle.com/r/WY3DlxF0/
Rent The Runway: https://rtr.app.link/e/rfHlXRUZuO

Want to BINGE?? Check out these playlists…

Quick Code Tutorials: https://www.youtube.com/watch?v=4K4QhIAfGKY&index=1&list=PLcLMSci1ZoPu9ryGJvDDuunVMjwKhDpkB

Command Line: https://www.youtube.com/watch?v=Jm8-UFf8IMg&index=1&list=PLcLMSci1ZoPvbvAIn_tuSzMgF1c7VVJ6e

30 Days of Code: https://www.youtube.com/watch?v=K5WxmFfIWbo&index=2&list=PLcLMSci1ZoPs6jV0O3LBJwChjRon3lE1F

Intermediate Web Dev Tutorials: https://www.youtube.com/watch?v=LFa9fnQGb3g&index=1&list=PLcLMSci1ZoPubx8doMzttR2ROIl4uzQbK

GitHub | https://github.com/blondiebytes

Twitter | https://twitter.com/blondiebytes

LinkedIn | https://www.linkedin.com/in/blondiebytes

#jsons #json arrays #json objects #what is json #jsons tutorial #blondiebytes

Samanta  Moore

Samanta Moore

1623835440

Builder Design Pattern

What is Builder Design Pattern ? Why we should care about it ?

Starting from **Creational Design Pattern, **so wikipedia says “creational design pattern are design pattern that deals with object creation mechanism, trying to create objects in manner that is suitable to the situation”.

The basic form of object creations could result in design problems and result in complex design problems, so to overcome this problem Creational Design Pattern somehow allows you to create the object.

Builder is one of the** Creational Design Pattern**.

When to consider the Builder Design Pattern ?

Builder is useful when you need to do lot of things to build an Object. Let’s imagine DOM (Document Object Model), so if we need to create the DOM, We could have to do lot of things, appending plenty of nodes and attaching attributes to them. We could also imagine about the huge XML Object creation where we will have to do lot of work to create the Object. A Factory is used basically when we could create the entire object in one shot.

As **Joshua Bloch (**He led the Design of the many library Java Collections Framework and many more) – “Builder Pattern is good choice when designing the class whose constructor or static factories would have more than handful of parameters

#java #builder #builder pattern #creational design pattern #design pattern #factory pattern #java design pattern

Lydia  Kessler

Lydia Kessler

1626209220

ULTIMATE Rust Lang Tutorial! - Common Collections

The ultimate Rust lang tutorial. Follow along as we go through the Rust lang book chapter by chapter.

📝 Get notified when the Rust Cheatsheet comes out: https://letsgetrusty.com/cheatsheet

The Rust book: https://doc.rust-lang.org/stable/book/​

0:00 Intro
0:39 Vectors
10:19 Strings
18:30 Hashmaps
24:21 Outro

#letsgetrusty​ #rust​lang #tutorial

#rust #rust lang #common collections

Autumn  Blick

Autumn Blick

1593251880

JSON Parsing in Android - Step by Step Implementation

JSON Structures in Android

JSON uses two types of brackets that are as follows:

  • [] – To declare the elements of Array in JSON, they’re written in square brackets.
  • {} – To create JSON objects, the elements are written in curly brackets.

JSON has the following types of structures that are:

1. JSON Objects

The elements inside the curly brackets are known as Objects.

2. JSON Array

A list of values, known as Arrays.

3. JSON Key-Value

This data is stored as a pair of keys and values. Here the keys can be a name, a number for which the values can be Seema, 98767586 etc.

Why JSON Parsing in Android over XML?

Let us see some reasons for why to choose JSON over XML:

  • It is much easier and quicker with high performance
  • It can use arrays
  • Its libraries do not depend on other libraries
  • The codes written in JSON are short, clean and easy to understand
  • It is free to open use and open-source tool
  • In JSON value retrieval is easy
  • It has a fully automated way of serializing/deserializing JavaScript.
  • It is supported by many Ajax toolkits and most of the backend technologies.

Examples of XML and JSON

Let us see the code difference of JSON and XML files:

XML Example:

<?xml version= “1.0” encoding= “” ?>
<student>
        <student>
  <name> Sia Sharma</name>
  <city> Chandigarh</city>
         </student>
        <student>
  <name>Dimple D’souza</name>
  <city> Nagpur</city>
         </student>
      <student>
  <name>Anna Jones</name>
  <city> Mumbai</city>
         </student>
  </student>

JSON Example:

{ “students”: [
{ “name”: “Sia Sharma”, “city”: “Chandigarh”},
{ “name”: “Prachi D’Souza”, “city”: “Nagpur”},
{ “name”: “Annas Jones”, “city”: “Mumbai”}
]}

I hope the difference is all clear in front of you. This is how simple JSON is and how easily it could be understood.

#android tutorials #json parsing in android #json parsing in android example #json parsing in android step by step #json parsing with android #read json file android