Home > Net >  Extract Value from a String? (JSON expression)
Extract Value from a String? (JSON expression)

Time:12-08

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\"}]}" 

CodePudding user response:

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"

CodePudding user response:

values[0].value

example:

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

console.log(obj.values[0].value)

CodePudding user response:

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".

  • Related