Domanda

Hi guys does anyone know how to write a regex that can look for tokens inside an json string?

{"testt":"{ccc}"}

Currently Im using

text.match(/\{([^\}]+)\}/gm)

I need to get just {ccc} not {"testt":"{ccc}

È stato utile?

Soluzione

IT seems like the tokens you want to find are in properties in quotes. It would be best to JSON.parse first and then look at properties and see if they match the expression, but you can search the raw JSON with something like:

text.match(/"\{([^\}]+)\}"/gm)

This assumes that the tokens start with "{ and end with }". You may also want to try:

text.match(/"\s*\{\s*([^\}]+)\s*\}\s*"/gm)

Altri suggerimenti

Depending on where the tokens are you could approach it in different ways. If your token's are always in quotations you could include those. The problem really comes down to it being super tricky with JSON because of the way the JSON format operates. If it's always on the value section of the json you might be able to get away with.

(?::)"?\{([^\}]+)\}

However, more than likely you'll need a better white list of tags your are explicitly looking for, rather than just the curly braces.

I noticed the first answer and posted this anyways. If the tags are outside of quotations they'll encounter the problem of the parser attempting to parse the {tag} as JSON.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top