klodoma
klodoma

Reputation: 4599

YAML Json over multiple lines

Let's look at the following YAML definition:

#yaml
---
user1:
    name: "User name"
    age: "adf"
    address:
        street: "some street"
        no: "23"
        postcode: "2341234"

user2: {name: "User name", age: "adf", address: { street: "some street", no: "23",  postcode: "2341234"}}

The user1 and user2 definitions are identical. I do prefer the user2 style sometimes, but when the definition becomes too long it's getting a problem to put everything in one line.

Is there a way of mixing JSON style on a multiline level? Something like:

user3: {name: "User name", age: "adf",
            address: { street: "some street", no: "23",  postcode: "2341234"}
       }

Upvotes: 5

Views: 9479

Answers (1)

Nick Roz
Nick Roz

Reputation: 4230

Yes, there is, but your programming language or parser implementation might not support this syntax.


Actually, you can do this, though I believe this line is not supposed to be well formatted one. It depends on what parser / programming language you use and whether the rules of it are strict or flexible.

According to YAML flow styles, YAML flow mappings and YAML docs, Example 2.6. Mapping of Mappings:

Mark McGwire: {hr: 65, avg: 0.278}
Sammy Sosa: {
  hr: 63,
  avg: 0.288
}

So as to verify I's possible I've just put this YAML (I left this code not properly formatted to be absolutely sure):

---
user1:
    name: "User name"
    age: "adf"
    address:
        street: "some street"
    no: "23"
    postcode: "2341234"

user2: {name: "User name", age: "adf", address: { street: "some street", no: "23",  postcode: "2341234"}}

user3: {name: "User name", age: "adf",
        address: { street: "some street", no: "23",  postcode: "2341234"}
    }

...to several online YAML validators.

Several of them validated is successfully:

And the next one didn't:

Also Ruby language (I haven't checked it via Perl, might be some of these online validators did this for me) allows this notation. Remember, that your programming language / parser might be syntax sensitive therefore this code will be wrong.

Personally, I wouldn't mix up different styles. The best way to my mind would be converting some lines to flow style, and some of them to plain:

user3:
    name: "User name",
    age: "adf",
    address: { street: "some street", no: "23",  postcode: "2341234" }

Upvotes: 3

Related Questions