如果列表中存在JSON键值,如何返回?

时间:2018-09-22 16:03:13

标签: python json

我正在尝试提取JSON键值(如果它们存在于列表中)。我正在使用Python,但没有得到任何结果。有什么明显的我想念的东西吗?下面提供了虚拟JSON数据,.js和当前的Python代码以供参考。谢谢!

{"int":1,"string":"Some string for int 1","date":"1969-1-1","metadata":"String metadata for int 1"}  
{"int":2,"string":"Some string for int 2","date":"1969-1-2","metadata":"String metadata for int 2"}  
{"int":3,"string":"Some string for int 3","date":"1969-2-1","metadata":"String metadata for int 3"}  
{"int":4,"string":"Some string for int 4","date":"1970-1-1","metadata":"String metadata for int 4"}  
{"int":5,"string":"Some string for int 5","date":"1969-1-1","metadata":"String metadata for int 5"}  

我想使用创建在.js文件中的“ int”键从该JSON文件中提取对象。 .js文件看起来就像:

2,5  

因此,使用此伪数据,我想要的输出将是包含以下内容的新编写的JSON:

{"int":2,"string":"Some string for int 2","date":"1969-1-2","metadata":"String metadata for int 2"}  
{"int":5,"string":"Some string for int 5","date":"1969-1-1","metadata":"String metadata for int 5"}

到目前为止,这是我的Python代码:

import json
import re

ids = open('dummy-ids.js', 'r').read().split(',')
dataset = set(ids)

with open('dummy2.json', 'r') as f:
    data = json.load(f)

for obj in data:
    if obj["id"] in dataset:
        print(obj)
    else:
        print(str(obj["id"]) + " not found")

以上代码导致未找到所有ID。让我知道是否有任何不清楚的地方。再次感谢!

2 个答案:

答案 0 :(得分:1)

您可以像这样遍历for obj in data: if obj['id'] in listof500: print(obj)

in

请注意,如果先将listof500转换为集合,则setof500 = set(listof500) for obj in data: if obj['id'] in setof500: print(obj) 运算符会更有效:

import React from "react";
import axios from "axios"; // For making client request.


class Form extends React.Component {
  constructor(props){
    super(props);
    this.state = {name: "", surname: "", email: "", message: ""};
  }

  handleForm = e => {
    axios.post(
      "https://formcarry.com/s/yourFormId", 
      this.state, 
      {headers: {"Accept": "application/json"}}
      )
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

    e.preventDefault();
  }

  handleFields = e => this.setState({ [e.target.name]: e.target.value });

  render() {
    return (
      <form onSubmit={this.handleForm}>
        <label htmlFor="name">Name</label>
        <input type="text" id="name" name="name" onChange={this.handleFields} />

        <label htmlFor="surname">Surname</label>
        <input type="text" id="surname" name="surname" onChange={this.handleFields} />

        <label htmlFor="email">Email</label>
        <input type="email" id="email" name="email" onChange={this.handleFields} />

        <label htmlFor="message">Your Message</label>
        <textarea name="message" id="message" onChange={this.handleFields}></textarea>

        <button type="submit">Send</button>
      </form>
    );
  }
}

export default Form;

答案 1 :(得分:0)

如果遵循您的代码,您应该是:

for i in range(3)

但是据我了解,您似乎正在找到交叉路口。如果它是真实的,那么您可以这样做:

import json
import re

listof500 = open('desiredIDs.js', 'r').read().split(',')

with open('toomanyIDs.json', 'r') as f:
    data = json.load(f)

for d in data.values():
    if d["id"] in listof500:
        print(each)