Descend JSON doc paths and update field names with jq

Descend JSON doc paths and update field names with jq

Content Index :

Descend JSON doc paths and update field names with jq
Tag : development , By : Patastroph
Date : November 28 2020, 04:01 AM

like below fixes the issue I'd like to descend, to any depth, all the paths in a MongoDB JSON doc and possibly modify each field name using jq (mongo shell doesn't seem capable of doing this.). Specifically, I'd like to remove all underscores ("_") in all field names except for "_id". I've tried various combinations of recurse and with_entries without success. So, e.g., transform this: , The simplest is to use walk:
walk( if type == "object"
      then with_entries( if .key != "_id" then .key |= gsub("_";"") else . end ) 
      else . end)
def camelcase:
  def u:  if 97 <= . and . <= 122 then . - 32  else . end;
  def c:
    if length <= 1 then
      if .[0] == 95 then [] else . end
    else if .[0] == 95 then [.[1]|u] + (.[2:] | c) else [.[0]] + (.[1:]|c) end

  explode | c | implode;
def camel_Case:
  if test("_")
  then .[0:1] as $first
  | if $first | (. ==  ascii_downcase)
    then $first | ascii_upcase + ([2:]|camelcase)
    else camelcase
  else .
  end ;

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to map JSON field names to different object field names?

Tag : java , By : Topher Cyll
Date : March 29 2020, 07:55 AM
I hope this helps . Probably it's a bit late but anyway..
you can rename a property just adding

Java JSON deserialize String with property names as field names

Tag : java , By : RichAA
Date : March 29 2020, 07:55 AM
Any of those help I am receiving from API json like that: , Declare Country class:
public class Country {
    private int uniques;
    private int views;
    private int viewtime;

    public int getUniques() {
        return uniques;

    public void setUniques(int uniques) {
        this.uniques = uniques;

    public int getViews() {
        return views;

    public void setViews(int views) {
        this.views = views;

    public int getViewtime() {
        return viewtime;

    public void setViewtime(int viewtime) {
        this.viewtime = viewtime;
public class Stats {

   private String channel;
   private Long startTime;
   private Long endTime;    
   private int totalUniques;
   private int totalViewtime;
   private int totalViews;
   private int totalCountries;


   private Map<String, Country> countries;

   public Map<String, Country> getCountries() {
       return countries;

   public void setCountries(Map<String, Country> countries) {
       this.countries = countries;

ObjectMapper mapper = new ObjectMapper();
Stats stats = mapper.readValue(jsonString, Stats.class);

MongoDB Shell Script Update all field Names where there is space in field name

Tag : mongodb , By : Tim
Date : March 29 2020, 07:55 AM
hop of those help? This needs a two-step approach. First, you need a mechanism to get a list of all the keys with a space in your collection. Once you get the list, construct an object that maps those keys to their renamed values. You can then use that object as your $rename operator document. Consider using mapReduce to get the list of keys with spaces.
The following mapReduce operation will populate a separate collection with all the filtered keys as the _id values:
mr = db.runCommand({
    "mapreduce": "CollectionName",
    "map": function() {
        var regxp = /\s/;
        for (var key in this) { 
            if (key.match(regxp)) {
                emit(key, null); 
    "reduce": function() {}, 
    "out": "filtered_keys"
["Some Field", "Another Field"]
var update = {
    "$rename": {
        "Some Field": "Some_Field",
        "Another Field": "Another_Field"        
var update = { "$rename": {} };
db[mr.result].distinct("_id").forEach(function (key){
    update["$rename"][key] = key.replace(/ /g,"_");
db.CollectionName.update({ }, update, false, true );

How to map JSON field names to Java object field names

Tag : java , By : Bo.
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You can use JsonProperty annotation as below so your clients can send request field name as FIRST_NAME and it can mapped to Employee class :
@Data // comes from lombok
class Employee {
    private String firstName;

//other fields

How to Pre Process Json String in Java :: Convert Capitalised Field names to lowerCase Camel case names

Tag : java , By : user179863
Date : March 29 2020, 07:55 AM
I hope this helps . I think you should really consider letting your JSON deserializer handle this, but if this really isn't a possibility you can always use good old string manipulation :
String input; // your JSON input
Pattern p = Pattern.compile("\"([A-Z])([^\"]*\"\\s*:)"); // matches '"Xxxx" :'
Matcher m = p.matcher(input);
StringBuffer output = new StringBuffer();
while (m.find()) {
   m.appendReplacement(output, String.format("\"%s$2", m.group(1).toLowerCase());
Related Posts Related QUESTIONS :
  • Manually polling streams in future implementation
  • How do you perform receipt validation for Android on Xamarin Forms
  • What is the rule behind instruction count in Intel PIN?
  • How to draw some text when click a button in wxWidgets?
  • Restrict entity types in Spacy NER
  • How to animate CN1 Slider progress on load
  • Issue with bwa mem process not running on all output files from previous process
  • Delete videos from playlist using YouTube API
  • How to restart the Hyperledger Composer Playground locally
  • How to configure email alerts in Zabbix Server?
  • Simulator is not working for smart home action with all configured session
  • How parse data using join on Objection.js
  • Assign an array to a property in a Chapel Class
  • Netlogo: How can I obtain the accumulate value in Netlogo?
  • How to populate datasource for listview using api response in react native?
  • Why does gmail API when using history.list method send message ids without the field what action has been preformed on t
  • How to run an append query in ms access vba as part of a transaction
  • Wrong dates shown in Jekyll-based blog
  • How to concatenate two document lists in a webMethods flow service?
  • How to properly set up a site map addition in a customization project
  • IBM Content Collector error calling external Web Service
  • Is (0*1*)* equal to (0 | 1)*?
  • How do I configure phpMyAdmin to start with a blank sql query from the SQL tab?
  • "Objects are not valid as a React child" Redux error when conditionally connecting a component?
  • Displacy results are not showing
  • Strapi / Graphql. What am i doing wrong?
  • How to add Search bar for django template?
  • lookup in presto using single column against a range in lookup table
  • How can you stop videos being stolen on website?
  • Can't code substitution happen in Hybrid Flow?
  • Removed widget remains on parent
  • setup saga middleware with redux-starter-kit's configureStore()
  • How to get cookies from response of scrapy splash
  • I need to do a firebase stream and not a Http Get
  • Unable to compile node-runtime
  • SQLSTATE[42S22]: Column not found: 1054 Unknown column '' in 'where clause'
  • How to extract only the number from a variable
  • disable linter in DAML studio
  • RxJS: How to set exhaustMap concurrent?
  • How to remove perforce (p4) on Ubuntu
  • How do they know mean and std, the input value of transforms.Normalize
  • Why this type is not an Interface?
  • SugarCRM Rest API set_relationship between Contacts and Documents
  • Jira dashboard organization
  • Web worker importScripts fails to place script variables in global scope
  • Always errors - The "path" argument must be one of type string, Buffer, or URL. Received type undefined
  • How to create an observable of a stream of infinite items
  • Not efficiently to use multi-Core CPU for training Doc2vec with gensim
  • webGL gl_Position value saving outside shaders
  • Is it okay for a resolver to have side effects besides resolving the type?
  • Move 32bit register into a 8 bit register
  • Is there a way to update, not overwrite, worker_env for a Dask YarnCluster within a script?
  • Lotus Notes Deployment
  • How Do I Add Active Directory To APIM Using Terraform?
  • How to get the old parameter values in Blazor OnParameterSet?
  • How to debug "ERROR: Could not reach the worker node."?
  • How chain indefinite amount of flatMap operators in Reactor?
  • extract dates and times from string in Redshift
  • How do I make a column of 3 cards match in height in bootstrapVue?
  • how to replace missing values from another column in PySpark?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com