pigsploof
pigsploof

Reputation: 35

Adding a prefix for each value in JSON dump

I'm creating a lexer which creates tokens and outputs them as a JSON list. The tokens are namedtuples.

More specifically, Token = namedtuple('Token', ['kind', 'lexeme'])

I create my tokens and print them using json.dumps(tokens, separators=(',', ':'))).

The output looks like this:

[
    [
      "INT",
      "123"
    ],
    [
      "ID" 
      "b32"
    ],
]

I am looking to add a 'kind' and 'lexeme' label so that it looks like:

[
    [
      "kind" : "INT",
      "lexeme" : "123"
    ],
    [
      "kind" : "ID" 
      "lexeme" : "b32"
    ],
]

Any ideas on how to do this?

Upvotes: 0

Views: 214

Answers (1)

gen_Eric
gen_Eric

Reputation: 227310

Convert the namedtuple to dict before running json.dumps().

json.dumps([t._asdict() for t in tokens], separators=(',', ':'))

This should generate:

[
    {
      "kind" : "INT",
      "lexeme" : "123"
    },
    {
      "kind" : "ID",
      "lexeme" : "b32"
    }
]

Try it online!

Upvotes: 1

Related Questions