skip to Main Content

I want to extract the value (.68) from this string.
How would I go about doing this?

{"values":[{"source":"source_value","value":".68"},    
{"source":"source.units","value":"%"},
{"source":"source_name","value":"Chemical"}]}

Currently, I have tried:

sub(".*:", "", df$value_as_string)

But I only get:

""Chemical"}]}" 

2

Answers


  1. Use the jsonStrings package to manipulate JSON strings:

    x <- '{"values":[{"source":"source_value","value":".68"}, {"source":"source.units","value":"%"}, {"source":"source_name","value":"Chemical"}]}'
    
    library(jsonStrings)
    
    jstring <- jsonString$new(x)
    
    jstring$at("values", 0, "value")
    # ".68"
    

    Explanation: "values", 0, "value" is the path to ".68". First the "values" key, where we found an array, then 0, the first element of this array, then "value", the key of ".68".

    Login or Signup to reply.
  2. The jsonlite package is another option.

    library(jsonlite)
    
    # note the single quotes to wrap the double quotes
    j <- fromJSON('{"values":[{"source":"source_value","value":".68"},    
                   {"source":"source.units","value":"%"},
                   {"source":"source_name","value":"Chemical"}]}')
    

    Now j$values is a data frame. Note that the value "0.68" is type character, not numeric.

    j$values  
            source    value
    1 source_value      .68
    2 source.units        %
    3  source_name Chemical
    
    j$values$value[1]
    [1] ".68"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search