Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • regular expression to extract json fields

    Hi, kindly asking for a hand , here.


    suppose, a simple Json object:


    {"title":"Title", {"data":"Data", {"foo": "Bar"}}

    and a regular expression:

    (?<="foo"\ *:\ *")(?:\"|[^"])*

    that matches "Bar" value.

    {"title":"Title", {"data":"Data", {"foo": "Bar"}}


    I have not been able to apply that in Stata

    Code:
    clear
    input str51 json
    `"{"title":"Title",  {"data":"Data", {"foo": "Bar"}}"'
    end
    
    . gen str9 foo = ustrregexs(0) if ustrregexm( json ,`"(?<="foo"\ *:\ *")(?:\\"|[^"])*"')
    (1 missing value generated)
    
    
    . list
    
         +----------------------------------------------------------+
         |                                               json   foo |
         |----------------------------------------------------------|
      1. | {"title":"Title",  {"data":"Data", {"foo": "Bar"}}       |
         +---------------------------------------------------------
    I guess I am not escaping "foo" double quotes correctly.

    thanks


  • #2
    Code:
    clear
    input str51 json
    `"{"title":"Title",  {"data":"Data", {"foo": "Bar"}}"'
    end
    
    
    gen wanted = ustrregexra(json, `".*\{"foo":\s(.*)\}\}"', "$1")
    Res.:

    Code:
    . l
    
         +-------------------------------------------------------------+
         |                                               json   wanted |
         |-------------------------------------------------------------|
      1. | {"title":"Title",  {"data":"Data", {"foo": "Bar"}}    "Bar" |
         +-------------------------------------------------------------+

    Comment

    Working...
    X