Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Match key-value json,Regex
#1
I want to replace either the matched key's value or the value matched with strings of the same length but consisting of * only.
There is no problem with Email. Email is fine but i could not figure out how to do the regex for "Name": "Jack", "Name":"Bethany"


This is my regular- expressions pattern:
regex_pattern = r'[\w\.\-]+@[\w\.\-]+'


import json
import re
jsonString =[{
	"Name": "Jack",
	"Email": "[email protected]"
},
{
	"Name": "Bethany",
	"Email": "[email protected]"
}
]

regex_pattern = r'[\w\.\-]+@[\w\.\-]+'

def database(jsonString, regex_pattern):
  s1 = json.dumps(jsonString)
  jsonObject = json.loads(s1)
  print(jsonObject)

  for key in range(len(jsonObject)):
    value = jsonObject[key]
    print("The key and value are ({}) = ({})".format(key, value))

    matchReg = re.findall(regex_pattern, str(jsonObject))
    print("matchReg: " ,matchReg)
    for mail in matchReg:
      print("Email: ", mail)


database(jsonString, regex_pattern)
This is result for email:
`Email: [email protected]
Email: [email protected]`

How to write regex for Name: Jack and Name: Bethany, any help would be appreciated.
[/python]
Reply
#2
I do not understand your request. Do you want to replace the *@domain.tld with [email protected]?

You could use normal str methods to split an E-Mail address into name and domain part, if this is your question.

Non-Pythonic code:
for key in range(len(jsonObject)) should be for key in jsonObject

This part is useless:
  s1 = json.dumps(jsonString)
  jsonObject = json.loads(s1)
  print(jsonObject)
You're converting the Python-list into a str as JSON representation.
Then you're loading the resulting str to get the Python-list.


Example:
# https://emailregex.com/
# modified to match name and domain
# regex_pattern = re.compile(r"([a-zA-Z0-9_.+-]+)@([a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)")


def database(data: list) -> None:

    for row in data:
        e_name, _, e_domain = row["Email"].rpartition("@")

        # possible replacements
        if e_name == "*":
            row["Email"] = f"{row['Name']}@{e_domain}"

        elif row["Name"] != e_name:
            row["Name"] = e_name

        print(row)


data = [
    {"Name": "Jack", "Email": "[email protected]"},
    {"Name": "Bethany", "Email": "[email protected]"},
    {"Name": "Foo", "Email": "*@red-gate.com"},
    {"Name": "", "Email": "[email protected]"},
]


database(data)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
Thank you @DeaD_EyE. first, I want to print separately for Name: Jack and Name: Bethany without email and then replace either the matched key's value or the value matched with strings of the same length but consisting of * only. Thanks if you could help.

For example:
with these files:

`json
[{
"Name": "Jack",
"Email": "[email protected]"
},
{
"Name": "Bethany",
"Email": "[email protected]"
}]
`

`json
["k:Name"]
`
produces
`json
[{
"Name": "****",
"Email": "[email protected]"
},
{
"Name": "*******",
"Email": "[email protected]"
}]
`
and
`json
["k:Name","v:[\\w+@\\w+.com]"]
`
produces
`json
[{
"Name": "****",
"Email": "****************"
},
{
"Name": "*******",
"Email": "********************"
}]
`
Reply
#4
(Dec-05-2021, 10:19 PM)saam Wrote: but i could not figure out how to do the regex for "Name": "Jack", "Name":"Bethany"

I don't really understand what you're trying to do, but using a regex to manipulate the JSON string is not the right approach. The correct thing to do is to load the JSON into data structures (i.e. with json.loads as you seem to be using) and then work on those.
Reply
#5
Hi @saam ,
I agree with the previous answers. You should not fiddle about with regex on a json string. Just use the tools the way they are made for.
You want to write a json file?
import json

jsonString =[{
    "Name": "Jack",
    "Email": "[email protected]"
    },
    {
    "Name": "Bethany",
    "Email": "[email protected]"
    }
]

with open("sample.json", "w") as fp:
    json.dump(jsonString, fp)
You want to print certain elements of the json data?
import json

with open("sample.json", "r") as fp:
    jsonString = json.load(fp)

for rec in jsonString:
    print(f"Name: {rec['Name']}")
Output:
Name: Jack Name: Bethany
You want to change the data?
import json

with open("sample.json", "r") as fp:
    jsonString = json.load(fp)

for rec in jsonString:
    rec['Name'] = "*" * len(rec["Name"])

for rec in jsonString:
    print(f"Name: {rec['Name']}")
Output:
Name: **** Name: *******
Please show us what you made of this. And if you get errors, show them too.
Reply
#6
Hi @ibreeden thank you for the reply. I want to produce this: I have tried to produce json with regex, I dont how to figure it out.

`json

[{
"Name": "****",
"Email": "****************"
},
{
"Name": "*******",
"Email": "********************"
}]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Facing issue in python regex newline match Shr 6 1,601 Oct-25-2023, 09:42 AM
Last Post: Shr
  Failing regex, space before and after the "match" tester_V 6 1,345 Mar-06-2023, 03:03 PM
Last Post: deanhystad
  Regex pattern match WJSwan 2 1,409 Feb-07-2023, 04:52 AM
Last Post: WJSwan
  Match substring using regex Pavel_47 6 1,575 Jul-18-2022, 07:46 AM
Last Post: Pavel_47
  regex.findall that won't match anything xiaobai97 1 2,123 Sep-24-2020, 02:02 PM
Last Post: DeaD_EyE
  regex on json file senaint 12 16,559 May-06-2020, 04:16 AM
Last Post: buran
  Creating new list based on exact regex match in original list interjectdirector 1 2,392 Mar-08-2020, 09:30 PM
Last Post: deanhystad
  regex match in a string batchen 4 3,353 Jan-20-2020, 08:48 AM
Last Post: batchen
  Regex to retrieve data from json in script tag. DreamingInsanity 4 9,750 Dec-20-2019, 06:18 PM
Last Post: DreamingInsanity
  json with regex script snagging mepyyeti 6 5,004 Feb-03-2018, 12:56 AM
Last Post: mepyyeti

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020