How to change values from JSONL file using Python?

Viewed 43

I have a JSONL file (that was created by an annotation I did using Prodigy) and it looks like this:

{
  "text": "More specifically, Haile 16A was suggested as most likely deriving from the early half of the late early Irvingtonian (1.6 to 1.3 Ma) by the use of mammalian biochronology (Morgan and Hulbert, 1995).",
  "spans": [
    {
      "start": 148,
      "end": 171,
      "token_start": 30,
      "token_end": 31,
      "label": "ACT_IMPLIED"
    }
  ]
}

I want to change tha value of "label", which is contained in "spans", from ACT_IMPLED to ACTIVITY.

I tried to do it using pandas but nothing changed. Here is my code:

import pandas as pd

path="/content/sample.jsonl"
data = pd.read_json(path, lines=True)

for idx, row in data.iterrows():
    for span in row.spans:
        if span['label'] == 'ACT_IMPLIED':
          span["label"].replace('ACT_IMPLIED', "ACTIVITY")
1 Answers

You can just use the json module once you have imported the json or dict.

it would look like this:

import json

j = {
  "text": "More specifically, Haile 16A was suggested as most likely deriving from the early half of the late early Irvingtonian (1.6 to 1.3 Ma) by the use of mammalian biochronology (Morgan and Hulbert, 1995).",
  "spans": [
    {
      "start": 148,
      "end": 171,
      "token_start": 30,
      "token_end": 31,
      "label": "ACT_IMPLIED"
    }
  ]
}

# change the value
j['label']='new value'

# write to file
with open('output.txt', 'w') as f:
     f.write(json.dumps(j))
Related