合并从 wordpress 导出的两个 Json 个文件

Combine two Json files exported from wordpress

我有两个 Json 从 wordpress 导出的文件,它们具有相应的 ID 我想将它们组合成一个 Json 文件,这样我就可以将它带到我用 Gatsby JS 构建的网站中。其中一个文件是 posts.json,另一个是 postsMeta.jsonpostsMeta中的post_id对应Posts

中的ID

我最好如何合并这两者?我可以在 js 中 运行 某种 for 循环吗?我该怎么做?我在 windows 是否有某种 json 资源管理器可以帮助我做到这一点。

最后我还想 trim 删除一些不必要的字段,例如 posts json 中的 post_parent 之类的postsMeta json.

中的 meta_key

好的,希望这已经足够清楚了,在此先感谢。

这里是两个文件中第一个对象对应对的例子

posts.json

{"ID":"19","post_author":"2","post_date":"2010-12-31 23:02:04","post_date_gmt":"2010-12-31 23:02:04","post_content":"Harry Potter was not available for the first sitting of the Halloween Picture. I hope everyone had a safe and fun Halloween. Tomorrow is picture retake day, please send back your previous prints if you want retakes. It is also hot lunch. See You tomorrow!","post_title":"Happy Halloween","post_excerpt":"","post_status":"publish","comment_status":"open","ping_status":"open","post_password":"","post_name":"happy-halloween","to_ping":"","pinged":"","post_modified":"2011-01-03 05:26:11","post_modified_gmt":"2011-01-03 05:26:11","post_content_filtered":"","post_parent":"0","guid":"http:\/\/localhost\/mrskitson.ca_wordpress\/?p=19","menu_order":"0","post_type":"post","post_mime_type":"","comment_count":"1"},

postsMeta.json

{"meta_id":"27","post_id":"19","meta_key":"large_preview","meta_value":"http:\/\/www.mrskitson.ca\/wp-content\/uploads\/2010\/12\/halloween.jpg"},

更新:

this是尝试用当前答案解决这个问题,你可以在那里编辑代码。

如果您可以在 js 中执行此操作,那么使用 Array#map 是一种非常简单的方法。如果您简化您的问题,您实际上是在询问如何在帖子的每个条目下添加此元数据,并仅获取您想要的字段。

我假设 posts.json 实际上是一个数组(例如 [{"ID":"19"....)。

// Load these server-side, fetch them remotely, copy-paste, etc.
// I'll require them here for simplicity
const posts = require('./posts.json');
const postsMeta = require('./postsMeta.json');

// Build a Map so we can quickly look up the metas by post_id
// Extract what we need by destructuring the args
const metaByPost = postsMeta.reduce((a, {
  post_id: id,
  meta_value: value,
}) => a.set(id, {
  value,
  /* anything else you want in here */,
}), new Map());

const mergedPosts = posts.map(post => ({
  // Spread in the post
  ...post,
  // Spread in the meta content
  ...metaByPost.get(post.ID),
  // Undefine the props we don't want
  post_parent: undefined,
}));

我不喜欢手动将东西设置为未定义——我认为明确说明你要包括哪些道具比加载所有东西并取消定义某些东西更好道具.

How would I best go about merging the two?

强制你把两者结合起来JSONfiles/data?

因为您可以只需要或加载脚本中的 JSON 数据(甚至将它们放在 HTML 中),然后获取特定元数据的元值 field/key,这个 function 可以做到这一点:

// `single` has no effect if `meta_key` is empty.
function getPostMeta( post_id, meta_key, single ) {
    let id = String( post_id ),
        pm = [];
    postsMeta.map( m => {
        let a = ( ! meta_key ) ||
            ( meta_key === m.meta_key );

        if ( a && id === m.post_id ) {
            pm.push( m );
        }
    });

    let meta = {},
        mk = {};
    pm.map( m => {
        let k = m.meta_key, v;

        if ( undefined === meta[ k ] ) {
            meta[ k ] = m.meta_value;
        } else {
            v = meta[ k ];
            if ( undefined === mk[ k ] ) {
                meta[ k ] = [ v ];
                mk[ k ] = 1;
            }

            meta[ k ].push( m.meta_value );
            m[ k ]++;
        }
    });

    pm = null;
    mk = meta_key ? mk[ meta_key ] : null;

    if ( mk ) {
        return single ?
            meta[ meta_key ][0] : // Returns a single meta value.
            meta[ meta_key ];     // Returns all the meta values.
    }

    return meta_key ?
        meta[ meta_key ] : // Returns the value of the `meta_key`.
        meta;              // Or returns all the post's meta data.
}

我用来测试的数据:(注意上面的postsMeta/getPostMeta()函数)

// Array of `post` objects.
const posts = [{"ID":"19","post_author":"2","post_date":"2010-12-31 23:02:04","post_date_gmt":"2010-12-31 23:02:04","post_content":"Harry Potter was not available for the first sitting of the Halloween Picture. I hope everyone had a safe and fun Halloween. Tomorrow is picture retake day, please send back your previous prints if you want retakes. It is also hot lunch. See You tomorrow!","post_title":"Happy Halloween","post_excerpt":"","post_status":"publish","comment_status":"open","ping_status":"open","post_password":"","post_name":"happy-halloween","to_ping":"","pinged":"","post_modified":"2011-01-03 05:26:11","post_modified_gmt":"2011-01-03 05:26:11","post_content_filtered":"","post_parent":"0","guid":"http:\/\/localhost\/mrskitson.ca_wordpress\/?p=19","menu_order":"0","post_type":"post","post_mime_type":"","comment_count":"1"}];

// Array of `meta` objects.
const postsMeta = [{"meta_id":"27","post_id":"19","meta_key":"large_preview","meta_value":"http:\/\/www.mrskitson.ca\/wp-content\/uploads\/2010\/12\/halloween.jpg"},{"meta_id":"28","post_id":"19","meta_key":"many_values","meta_value":"http:\/\/facebook.com"},{"meta_id":"29","post_id":"19","meta_key":"many_values","meta_value":"http:\/\/twitter.com"},{"meta_id":"30","post_id":"19","meta_key":"many_values","meta_value":"http:\/\/linkedin.com"}];

示例:(有关演示,请参阅 this Fiddle

// In these examples, we are retrieving the meta value for the post #19 (i.e. ID is 19).

// Retrieve a single value.
// Returns mixed; string, number, etc.
let url = getPostMeta( 19, 'large_preview', true );
console.log( url );

// Retrieve all meta values.
// Always returns an array of values.
let ms = getPostMeta( 19, 'many_values' );
console.log( ms, ms[0] );

// Retrieve all meta data.
// Always returns an object with meta_key => meta_value pairs. I.e. { key => value, ... }
let ma = getPostMeta( 19 );
console.log( ma, ma.large_preview, ma.many_values[0] );

但如果你真的必须合并 JSON 数据,你可以这样做:(再次参见 the same Fiddle 上的演示)

// Here we modify the original `posts` object.
posts.map( p => {
    // Add all the post's meta data.
    p.meta = getPostMeta( p.ID );

    // Delete items you don't want..
    delete p.post_parent;
    delete p.menu_order;
    // delete ...;
});

console.log( JSON.stringify( posts[0].meta ) ); // posts[0].meta = object
console.log( posts[0].post_parent, posts[0].menu_order ); // both are undefined

然后如果你想复制粘贴新的/merged JSON 数据:

JSON.stringify( posts );

但是如果你真的只是想用post的元做一些事情,你可以遍历posts对象并做这件事;例如:

// Here the original `posts` object is not modified, and that we don't
// (though you can) repeatedly call `getPostMeta()` for the same post.
posts.map( p => {
    // Get all the post's meta data.
    let meta = getPostMeta( p.ID );

    // Do something with `meta`.
    console.log( meta.large_preview );
});

console.log( JSON.stringify( posts[0].meta ) ); // posts[0].meta = undefined
console.log( posts[0].post_parent, posts[0].menu_order ); // both still defined

// posts[0].meta wouldn't be undefined if of course posts[0] had a `meta` item,
// which was set in/via WordPress...

直接在 Chrome DevTools 控制台中尝试此代码段:

(function(
  postsUrl='https://cdn.glitch.com/61300ea6-6cc4-4cb6-a62f-31adc62ea5cc%2Fposts.json?1525386749382',
  metaUrl='https://cdn.glitch.com/61300ea6-6cc4-4cb6-a62f-31adc62ea5cc%2Fpostmeta.json?1525386742630'
) {
  Promise.all([
    fetch(postsUrl).then(r => r.json()),
    fetch(metaUrl).then(r => r.json()),
  ]).then(([postsResponse, metaResponse]) => {
    // Inspected the actual JSON response to come up with the data structure
    const posts = postsResponse[2].data;
    const meta = metaResponse[2].data;
    const metaByPostId = meta.reduce((accum, el) => {
      accum[el.post_id] = el;
      return accum;
    }, {});
    const transformedPosts = posts.map(post => {
      const merged = {
        ...post,
        ...(metaByPostId[post.ID] || {}),
      };
      delete merged.post_parent;
      // delete any other fields not wanted in the result
      return merged;
    });
    console.log(transformedPosts);
  });
})();
  • 相应地替换 URL,我在这里使用了 Glitch 示例中的那些
  • 如评论所述,实际数据隐藏在 response[2].data 中。使用网络选项卡/解析视图查看结构
  • console.log 替换为 copy,如果您希望将结果复制到剪贴板,而不是记录到控制台

针对你的问题开门见山。我们想要:

  • var a = {/*some json*/}合并到var b = {/*another json*/}
  • trim var exclusions = ["post_parent","meta_key"]
  • 字段

合并JSONS

首先,我们需要填充a和b。 您的 JSON 可以解析为 Javascript 个对象 JSON.parse():

let a = JSON.parse(/*JSON here*/);
let b = JSON.parse(/*JSON here*/);

因为属性在 Javascript 中的定义方式,如果您再次定义 属性,第二个定义将覆盖第一个。您的 JSONS 仅包含作为键的字符串和作为值的字符串,因此 shallow copy will suffice. Object.assign() 会将所有属性(字段和值)复制到第一个参数和 return 最终对象中。因此这会将 a 合并到 b,假设它们具有不同的键,否则 b 中的值将覆盖 a 中的值:

a = Object.assign(a,b);

否则,如果它们不相交,您必须定义一些关于如何加入的策略,例如可以优先考虑一个。下面,我们将值保留在 a 中:

a = Object.assign(b,a);

因为你提到了一个 for 循环,下面的行与上面的两行代码行相同,并且还可以向你展示如何编写你的代码的示例自己的自定义 lambda 表达式:

Object.keys(a).forEach(k=>b[k]=b[k]?b[k]:a[k]);

不想碰 ab?创建第三个对象 c.

let c = Object.assign({},a,b)

最后(等到下面的 trim 步骤完成)JSON.stringify() 会将合并后的对象转换回 JSON。

Trim 排除项

按照第三个例子,我们c与所有字段合并。

首先是来自 here 的一些技巧:

Object.filter = (obj, predicate) => Object.keys(obj)
    .filter( key => predicate(obj[key]))
    .reduce( (res, key) => (res[key] = obj[key], res), {} );

现在对象,就像数组一样有一个过滤器原型,具有扩展的对象原型。这不是真正的最佳实践,因为这将扩展每个对象,但这个函数在 Javascript 的语义方面工作得很好,这个例子提供了一个机会来保持优雅的 Javascript 样式代码:

c = Object.filter(c, key=> !exclusions.includes(key) );

Voit-lá,完成。

至于定义的 Object.filter() 它使用 Array.filter() and Array.reduce() 。点击参考,方便您使用。