-2

I need to extract a json from a console output that looks like that :

[main] Lin of log 1
[main] Lin of log 2
...
[main] Lin of log n
{
    "jsonProperty1": "aString",
    "jsonNestedObject1": {
        ...
    },
    ...
    "jsonPropertyN": "something"
}
[main] Lin of log n+1
...
[main] Lin of log m

I want to write this JSON object in an "input.json" file, how can I do this using commands like awk, grep or sed please ?

Thank you in advance for your help

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • I don't know why I'm getting downvoted, I think it would be more constructive to also explain why you think this question isn't good with a comment please :) – Virgile Petermann Apr 13 '21 at 11:21
  • 1
    Welcome to SO! Please show us what you have tried so far. Not my downvote BTW. – Thomas Hansen Apr 13 '21 at 12:34
  • 1
    A lot of ellipses there. By *"this JSON object",* Do you mean the curly braces and the text between them? Are those the only curly braces in the source? Are there perhaps curly braces *inside* that block? If there are other JSON objects in the source, can you tell us what distinguishes this one from the others? – Beta Apr 13 '21 at 13:44
  • @ThomasHansen Thank you ! Well I'm not an expert in shell programming, so I made researches, but the solutions I found were not adapted. The closest I got was with ```awk '/{/,/}/'```, but I don't know why, it did not match until the end. The others I tried were just a huge mess, matching only the brackets, and not the text between them :/ – Virgile Petermann Apr 13 '21 at 14:15
  • @Beta Thanks for your precisions, yes by JSON object I mean the braces and the text between them, they are the only curly braces od the source, they are other curly braces inside that block, and this is the only JSON of the source. I tried to make it as understandable as I could on my exemple, sorry if it wasn't precise enough :) – Virgile Petermann Apr 13 '21 at 14:19

2 Answers2

1

Please try the following:

awk '/^{$/{f=1}f{print; if(/^\}$/) f=0}' input > input.json

Explanation: When { is found, f is set. With f true lines are printed, but if } is found, f is unset, and printing stops. For further reading, please check out Is a /start/,/end/ range expression ever useful in awk?

Thomas Hansen
  • 775
  • 1
  • 6
  • 17
0

Here is a sed solution:

sed -n '/{/,/^}/p' input > input.json

This translates as "don't print anything in general, but from the first opening brace to the first closing brace that comes at the beginning of a line, print everything."

Beta
  • 96,650
  • 16
  • 149
  • 150
  • Thank you very much ! Is there any reason to pick one solution above the other one, or is it exaclty the same ? – Virgile Petermann Apr 14 '21 at 10:34
  • @VirgilePetermann: there are several good criteria you can go by; in this case I think you should pick the solution that seems easier to understand and use. – Beta Apr 14 '21 at 13:37