-2

I have a JSON stored as a string like this one :

message = """{"info":{"keyVersion":1,"timestamp":"2020-11-05 20:00:00","encryptedData":"75657374696f6e732068617665207265636569"},"mac":"4d6163204b65792049732048455245"}"""

My goal is to compute the MAC value of the data stored in "info" part. The mac is computed on the string :

{"keyVersion":1,"timestamp":"2020-11-05 20:00:00","encryptedData":"75657374696f6e732068617665207265636569"}

When I try to parse the JSON 'message' using json.loads, than extract the info part and set it back as a string, the new string has a different formatting. Here is my part of code :

parsed_message = json.loads(message)
info_part = parsed_message["info"]
print json.dumps(info_part)

the result is :

{"encryptedData":"75657374696f6e732068617665207265636569", "keyVersion":1, "timestamp":"2020-11-05 20:00:00"}

When I compute the mac value on this new string I don't get the same result as the mac in the initial message (as there is more data in it and field order is different).

I'm looking for a way to extract only the info part as a string, as it is provided in the original message. I tried to use regex but I'm confusing myself counting " and {}

Thank you in advance for your help !

Cyril
  • 1
  • 1

1 Answers1

-1

Try this:

(?<=info\":).*(?=,\"mac\")

Demo

python3 code:

import re

test = """{"info":{"keyVersion":1,"timestamp":"2020-11-05 20:00:00","encryptedData":"75657374696f6e732068617665207265636569"},"mac":"4d6163204b65792049732048455245"}"""
print(*re.findall(r"(?<=info\":).*(?=,\"mac\")", test))

Demo

Alireza
  • 2,103
  • 1
  • 6
  • 19