I have the following data structure with p1-24, with v1-v8 files for each 24 folders.
Each JSON file contains 1 object with around 10 key/pair values (some values are lists, some strings, some numbers).
Abbrv example:
> p1
> --p1_v1.json
> --p1_v2.json
> --p1_v3.json
> --p1_v4.json
> p2
> --p2_v1.json
> --p2_v2.json
> --p2_v3.json
> --p2_v4.json
Original json:
> { “Element1”: info,
> “Element2”: info,
> “Element3”: [
> Info1,
> Info2,
> Info3]
> }
I need to add a key/value pair (the value is a list of 15 numbers) to every json file. So each json will contain a copy of the same additional element (which is not unique per file).
New element:
> “AdditionalElement: [
> 0.998,
> 0.768,
> 0.394,
> 0.123]
>
>
So I’d like to end up with this for all of the json files
> “Element1”: info,
> “Element2”: info,
> “Element3”: [
> Info1,
> Info2,
> Info3],
> “AdditionalElement: [
> 0.998,
> 0.768,
> 0.394,
> 0.123]
> }
I have tried using jsonStrings and $addproperty, which works perfectly for one json file. but I need to add the element to every json file and then save the edits back to the original files/ folders.
I have tried this:
` files <- list.files("P:/new", recursive=T, full.names = TRUE, pattern = ‘sub.*.json$’)
files
json_lst <- lapply(jsonString$new(files)
newlist <- lapply(jsonString$addProperty("newelement", "[5, 6, 3, 2, 7]")`
2
Answers
Using a
fromJSON / append / toJSON
approach. Weappend
the vector as a namedlist
element.append
defaults toafter=length(x)
, so it’s automatically appended to the end.Gives
Note: To read in your actual .json files (I used the example below) do sth. like:
To write back to file use
Data:
You don’t need to parse the JSON string to a R object if you use the jsonStrings package:
EDIT
For your files: