请求生成多行JSON格式的REGEX,移除attributes保留Account的Name
If you need to strip out all attributes objects from your Account entries while retaining only the Name field, here's a robust regex solution that handles common whitespace variations in JSON:
Regex Pattern
/"attributes"\s*:\s*\{\s*.*?\s*\}\s*,?/gs
Breakdown of the Pattern
"attributes": Matches the exact key name for the object we want to remove.\s*: Accounts for any number of whitespace characters (spaces, tabs, newlines) before and after the colon.:\s*\{: Matches the colon leading into the attributes object, followed by any whitespace and the opening curly brace..*?: Non-greedy match for all content inside the attributes object (ensures we don't accidentally capture content beyond the closing brace).\s*\}: Matches any whitespace followed by the closing curly brace of the attributes object.,?: Optional comma to handle the separator between the attributes object and theNamefield (since attributes come right beforeNamein your structure).gsflags:gfor global replacement (targets all occurrences),sto make the dot (.) match newline characters (works for both minified and pretty-printed JSON).
Usage Example
Input JSON
{ "Accounts":[ { "attributes":{ "type":"Account", "url":"/services/data/v41.0/sobjects/Account/001S0000008mgjpIAA" }, "Name":"Name+Test#Reseller" }, { "attributes":{ "type":"Account", "url":"/services/data/v41.0/sobjects/Account/001S000000m5gyuIAA" }, "Name":"Test Reseller Myself" } ] }
Replacement Result
After applying the regex replacement (replace matches with an empty string), you'll get:
{ "Accounts":[ { "Name":"Name+Test#Reseller" }, { "Name":"Test Reseller Myself" } ] }
Important Note
While this regex works perfectly for your specific JSON structure, regex is not the ideal tool for general JSON manipulation (it can fail if the JSON structure varies unexpectedly, like nested objects inside attributes or different ordering of keys). For production code, it's always better to parse the JSON with a dedicated JSON library, modify the object structure, then re-serialize it. But for quick one-off edits or cases where regex is your only option, this pattern will get the job done.
内容的提问来源于stack exchange,提问作者mohammed azarudeen

